TypeScriptでReactのチュートリアルをやる
まずはプロジェクトの生成
npx create-react-app my_app --template typescript
次はチュートリアルの流れで削除
cd src
rm -rf *.*
jsとcssをコピペしつつ書き換えのために調べる
index.js
index.css
というか.ts
と.tsx
ってなにが違うんだ?
.ts
TypeScriptのファイル
.tsx
JSXの記述があるTypeScriptのファイル
なるほど(JSXってなんだ?
JSX
JavaScriptの構文の拡張
const element = <h1>Hello, world</h1>
javascriptでは初めから.js
でJSX記法を使っているが、TypeScriptでは.tsx
とする必要があると完全理解
チュートリアルでコピペで必要なのは、index.tsx
とindex.css
になる
とりあえずのエラー箇所は二つ
RROR in src/index.tsx:12:16
TS7006: Parameter 'i' implicitly has an 'any' type.
10 |
11 | class Board extends React.Component {
> 12 | renderSquare(i) {
| ^
13 | return <Square />;
14 | }
15 |
ERROR in src/index.tsx:60:34
TS2345: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'.
Type 'null' is not assignable to type 'Element | DocumentFragment'.
58 | // ========================================
59 |
> 60 | const root = ReactDOM.createRoot(document.getElementById("root"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
61 | root.render(<Game />);
62 |
一つ目は、renderSquare
の型エラー
anyゆるせん!!
number型付けをして回避
renderSquare(i: number) {
2つ目は、document.getElementById("root")
の型エラー
nullが入るのはいかがか!!
HTMLElementのキャストして回避
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement,
);
Square
クラスにvalue
を渡すだけで大騒ぎだ
ERROR in src/index.tsx:13:20
TS2769: No overload matches this call.
Overload 1 of 2, '(props: {} | Readonly<{}>): Square', gave the following error.
Type '{ value: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Square> & Readonly<{}>'.
Property 'value' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Square> & Readonly<{}>'.
Overload 2 of 2, '(props: {}, context: any): Square', gave the following error.
Type '{ value: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Square> & Readonly<{}>'.
Property 'value' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Square> & Readonly<{}>'.
11 | class Board extends React.Component {
12 | renderSquare(i: number) {
> 13 | return <Square value={i} />;
| ^^^^^
14 | }
15 |
16 | render() {
クラスに型を付けることで回避
type SquareProps = {
value: number;
};
class Square extends React.Component<SquareProps> {
インタラクティブなコンポーネントを作る
onClick
にconsole.log
を設定
class Square extends React.Component<SquareProps> {
render() {
return (
<button className="square" onClick={() => console.log("click")}>
{this.props.value}
</button>
);
}
}
これは型が必要ないから大丈夫
コンストラクタの追加とstateの初期化なんだけど、そこconstructor
の型じゃなかったの…?
class Square extends React.Component<SquareProps> {
constructor(props) {
class Square extends React.Component<SquareProps> {
constructor(props) {
super(props);
this.state = {
value: null,
};
}
State
への型追加とpros
への型宣言の追加
type SquareProps = {
value: number;
};
type SquareState = {
value: string | null;
};
class Square extends React.Component<SquareProps, SquareState> {
constructor(props: SquareProps) {
super(props);
this.state = {
value: null,
};
}
良いものを見付けた(初期化のみならチートシートと同じくconstructor
いらんよな…
Stateのリフトアップ
Board
クラスにconstructor
を追加
props
は側だけ
type BoardProps = {};
type BoardState = {
squares: string | null[];
};
class Board extends React.Component<BoardProps, BoardState> {
constructor(props: BoardProps) {
super(props);
this.state = {
squares: Array(9).fill(null),
};
}
SquarePropsがnumber
だったのでエラーはいた
ERROR in src/index.tsx:45:20
TS2322: Type 'string | null' is not assignable to type 'number'.
Type 'null' is not assignable to type 'number'.
43 |
44 | renderSquare(i: number) {
> 45 | return <Square value={this.state.squares[i]} />;
| ^^^^^
46 | }
47 |
48 | render() {
valueの型をstring | null
にしてヨシッ!
renderSquare(i: number) {
return <Square value={this.state.squares[i]} />;
}
type SquareProps = {
value: string | null;
};
Board
からonClick
を渡すように変更
SquareProps
型にonClick
の関数を追加
type SquareProps = {
value: string | null;
onClick: () => void;
};
renderSquare(i: number) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
-
Square
からconstructor
を削除 -
SquareState
を削除 -
handleClick
を追加
class Square extends React.Component<SquareProps> {
render() {
return (
<button className="square" onClick={() => this.props.onClick()}>
{this.props.value}
</button>
);
}
}
handleClick(i: number) {
const squares = this.state.squares.slice();
squares[i] = "X";
this.setState({ squares: squares });
}
関数コンポーネント
function Square(props: SquareProps) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
手番の処理
-
BoardState
型にxIsNext
を追加
type BoardState = {
squares: Array<string | null>;
xIsNext: boolean;
};
class Board extends React.Component<BoardProps, BoardState> {
constructor(props: BoardProps) {
super(props);
this.state = {
squares: Array(9).fill(null),
xIsNext: true,
};
}
handleClick(i: number) {
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({ squares: squares, xIsNext: !this.state.xIsNext });
}
render() {
const status = `Next player: ${this.state.xIsNext}`;
ゲーム勝者の判定
- 勝利判定関数の追加
-
Squares
型を追加してまとめてる
handleClick(i: number) {
const squares = this.state.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({ squares: squares, xIsNext: !this.state.xIsNext });
}
render() {
const winner = calculateWinner(this.state.squares);
let status;
if (winner) {
status = "Winner: " + winner;
} else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
type Squares = Array<string | null>;
type BoardState = {
squares: Squares;
xIsNext: boolean;
};
function calculateWinner(squares: Squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
Stateのリフトアップ、再び
Gameにconstructorを追加
type GameProps = {};
type GameState = {
history: Array<{ squares: Squares }>;
xIsNext: boolean;
};
class Game extends React.Component<GameProps, GameState> {
constructor(props: GameProps) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
},
],
xIsNext: true,
};
}
Gameの変更に伴うBoardの修正
- Boardの
constructor
の削除 - Boardの
state
参照をprops
に変更 -
handleClick
を削除 -
BoardState
型を削除 -
BoardProps
型にonClick
を追加
type BoardProps = {
squares: Squares;
onClick: (i: number) => void;
};
class Board extends React.Component<BoardProps> {
renderSquare(i: number) {
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
Gameで最新状態が表示されるように変更
-
history
から最新を取得 - Boardに
onClick
を渡す -
state
の表示
render() {
const history = this.state.history;
const current = history[history.length - 1];
const winner = calculateWinner(current.squares);
let status: string;
if (winner) {
status = `Winner: ${winner}`;
} else {
status = `Next player: ${this.state.xIsNext ? "X" : "O"}`;
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
GameにhandleClick
を追加
handleClick(i: number) {
const history = this.state.history;
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([{ squares: squares }]),
xIsNext: !this.state.xIsNext,
});
}
過去の着手の表示
- 過去着手の表示を追加
- 仮で関数を追加
jumpTo(step: number) {}
render() {
const history = this.state.history;
const current = history[history.length - 1];
const winner = calculateWinner(current.squares);
const moves = history.map((_, move) => {
const desc = move ? `Go to move #${move}` : `Go to game start`;
return (
<li>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
let status: string;
if (winner) {
status = `Winner: ${winner}`;
} else {
status = `Next player: ${this.state.xIsNext ? "X" : "O"}`;
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
li
にkey
を設定
const moves = history.map((step, move) => {
const desc = move ? `Go to move #${move}` : `Go to game start`;
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
GameにstepNumber
を追加
-
GameState
型にstepNumber: number
を追加
type GameState = {
history: Array<{ squares: Squares }>;
stepNumber: number;
xIsNext: boolean;
};
class Game extends React.Component<GameProps, GameState> {
constructor(props: GameProps) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
},
],
stepNumber: 0,
xIsNext: true,
};
}
jumpTo
の機能を実装
jumpTo(step: number) {
this.setState({
stepNumber: step,
xIsNext: step % 2 === 0,
});
}
handleClick
で過去の状態に移動できるように変更
handleClick(i: number) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([{ squares: squares }]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
render
でstepNumber
の盤面を参照するように変更
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
これにてtypescriptでのReactチュートリアルDone
別途確認したいこと
-
useState
を組込むとどうなるのか - 空の型を定義したが、直接
{}
と定義した方がよかったか
:eye:
反省点
- 型の切り方がわるかった
- 型の命名がわるかった
useState
も使ってるので参考になる
- type
- interface