LoginSignup
2
2

More than 5 years have passed since last update.

flowtypeについて

Last updated at Posted at 2018-01-07

flowとは

javascriptの型チェックライブラリ。

flowの型定義ファイルの取得

package.jsonに記載された各ライブラリについての、flowの型定義ファイルを取得する。
取得した型定義ファイルはflow-typedディレクトリ内に格納される。
型定義ファイルが無い場合、ライブラリをimportしたときにflowの型チェックエラーとなる。

yarn global add flow-bin ※初回のみ実施
.\node_modules\.bin\flow-typed install

flowの適用

ソースの冒頭に以下のコメントを記述するとflowの型チェックが有効となる。

// @flow

ReactコンポーネントのPropsをflowでチェックする

type Propsの中にPropsの型を定義する。

import TestClass as './TestClass';

type Props = {
  name: string,
  age?: string,
  action: any,
  ...$Exact<Props>,
  testClass: TestClass,
};

const Sample = (props: Props) => (
  <div>
    {props.name}
    <button onClick={() => props.action()}>Button<\button>
    <ChildSample {...props} />
    {props.testClass.age()}
  </div>
);

export default Sample;
  • functionはany型
  • propsの展開({...props})は、...$Exact型
  • 独自オブジェクト(例で言うTestClass)は、オブジェクトをimportして型定義する。
  • 必須でないプロパティは、age?のように末尾に?を付ける。
  • コンポーネントの引数に(props: Props)と書いて、Props型とprops変数を紐づける。

eslintの設定

eslintを使用している場合、flowでチェックエラーとならないよう、.eslintrcを修正する。

.eslintrc
  "extends": [
    ・・・
    "plugin:flowtype/recommended" ←追加
  ],
  "plugins": [
    "flowtype"
  ],
  "rules": {
    "flowtype/no-types-missing-file-annotation": 0,
    "flowtype/define-flow-type": 1,
    "flowtype/use-flow-type": 1,
    "react/prop-types": [off],
    "react/default-props-match-prop-types": [off]
  },
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2