React はコンポーネント単位である web ページのHTML、JavaScript、CSSを定義できる JavaScript ライブラリです。
React – ユーザインターフェース構築のための JavaScript ライブラリ
コンポーネント間では Props という仕組みでデータを受け渡します。
チュートリアル:React の導入 – React#データを Props 経由で渡す
これの実装は次の様なコードになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 親コンポーネントで Square を呼び出し, key:len, value: 5 な値を渡す class Board extends React.Component { render() { return <Square len={5} />; } } // 子コンポーネントで this.props.len として渡された値を呼び出す class Square extends React.Component { render() { return ( <button className= "square" > { this .props.len} </button> ); } } |
React で用いられる JSX 記法とプロパティのつかめないオブジェクト this.props があわさり、両方の実装かコメントを見ないと何が渡され、何を読もうとしているのかわかりません。このままでも動きはしますが開発に時間がかかってしまいます。これを解決する方法の一つが TypeScript による型指定です。
1 2 3 4 5 6 7 8 9 10 11 12 13 | type SquareState = {} type SquareProps = { len: number } class Square extends React.Component<SquareProps,SquareState> { render() { return ( <button className= "square" > { this .props.len} </button> ); } } |
上記コード例の様に React.Component のジェネリクスに Props と State の型を渡すことで TypeScript として Props と State に関して型チェックが働くようになり、IDE や TypeScript による異常検知や予測補完ができる様になります。
便利ですが時には TypeScript が使えないこともあります。そういった時には prop-types というライブラリが使えます。
facebook/prop-types: Runtime type checking for React props and similar objects
prop-types は React の主要な開発元である Facebook 主導で作られている Props の type を定義するためのライブラリです。これを次の様に静的プロパティとして Component に引っ付けてやれば JavaScript のままでも補完ができる様になります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import React, {Component} from 'react' ; import PropTypes from 'prop-types' ; class Square extends Component { // 内部で定義 static propTypes = { len: PropTypes.number.isRequired, } render() { return ( <button className= "square" > { this .props.len} </button> ); } } // あるいは class SquareSecond extends Component { render() { return ( <button className= "square" > { this .props.len} </button> ); } } // 静的プロパティとして後付けで定義 SquareSecond.propTypes = { len: PropTypes.number.isRequired, } // 呼び出しは素と同じ class Board extends React.Component { render() { return <Square len={5} />; } } |
prop-types によって指定できる型は多岐に渡ります。その型の使い方は GitHub の Usage や React 本体のドキュメントに載っています。
facebook/prop-types: Runtime type checking for React props and similar objects#Usage
Typechecking With PropTypes – React