UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【FlowType】逆引きメモ

Flow使ってみて調べた使い方

分割代入した変数に対して

const { pathname }: { pathname: string } = location;

指定された型をすべて満たす型をつくる

Intersection types を使う

// @flow
type A = { a: number };
type B = { b: boolean };
type C = { c: string };

function method(value: A & B & C) {
  // ...
}

// $ExpectError
method({ a: 1 }); // Error!
// $ExpectError
method({ a: 1, b: true }); // Error!
method({ a: 1, b: true, c: 'three' }); // Works!

指定された型のうちどれか1つを満たす型をつくる

Union types を使う

// @flow
function toStringPrimitives(value: number | boolean | string) {
  return String(value);
}

toStringPrimitives(1);       // Works!
toStringPrimitives(true);    // Works!
toStringPrimitives('three'); // Works!

// $ExpectError
toStringPrimitives({ prop: 'val' }); // Error!
// $ExpectError
toStringPrimitives([1, 2, 3, 4, 5]); // Error!

EnumのようなUnion型を生成する

$Keysを使う

// @flow
const countries = {
  US: "United States",
  IT: "Italy",
  FR: "France"
};

type Country = $Keys<typeof countries>;

const italy: Country = 'IT';
const nope: Country = 'nope'; // 'nope' is not a Country