LoginSignup
0
0

More than 5 years have passed since last update.

FlowTypeでオブジェクトを渡すときのプロパティの書き方まとめ

Posted at

FlowTypeでオブジェクトを渡すときのプロパティの書き方による違い。

// @flow

// a はないといけないけど、undefinedやnullでもOK
function hoge(x: { a: ?number }) {}
hoge({a:1});
hoge({a:1, b:1});
hoge({}); // bug?
// hoge({b:1});   // error
hoge({a: undefined});
hoge({a: null});

// aはあってもなくてもよい
function hoge2(x: { a?: number }) {}
hoge2({a:1});
hoge2({a:1, b:1});
hoge2({});
hoge2({b: 1});
hoge2({a: undefined}); // undefined はないのと同じ扱い
// hoge2({a: null}); // error aというプロパティがある以上numberでないといけない。

// aはないといけない
function hoge3(x: { a: number }) {}
hoge3({a:1});
hoge3({a: 1, b:1});
hoge3({}); // bug?
// hoge3({b:1}); // error
// hoge3({a: undefined}); // error aがある以上numberないといけない
// hoge3({a: null}); // error

// nullをゆるしちゃうぞ
function hoge4(x: { a: number | null }) {}
hoge4({a:1});
hoge4({a: 1, b:1});
hoge4({});  // bug?
// hoge4({a: undefined}); // error
hoge4({a: null}); // nullを許容することができる

// 他のがあったらだめ
function hoge5(x: {| a: number |}) {}
hoge5({a:1});
// hoge5({a: 1, b:1}); // error
// hoge5({}); // error 
// hoge5({a: undefined}); // error
// hoge5({a: null}); // error

{}が渡せちゃうのはバグっぽいけどどうなんだろうか。
実際にこまることはめったにななさそうだけど。

0
0
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
0
0