flow の changelog を週1ぐらいで眺めているのだが、サポートされたときいてマジかとなった
Type support for the Stage 1 Optional Chaining proposal. To use this feature, set esproposal.optional_chaining=enable in your .flowconfig.
言われたとおりに、 .flowconfig に esproposal.optional_chaining=enable
追加し、 https://www.npmjs.com/package/babel-plugin-transform-optional-chaining を .babelrc に導入したが、動かない…
調べると optional-chaining は babel7 を使えということになっていたので、babel7にアップデートし(ここでjest/webpack/storybookの対応で1日かかった。覚悟が必要) 次のプラグインを .babelrc.js に追加
yarn add @babel/plugin-proposal-optional-chaining -D
/* @flow */
type Foo = {
a?: {
b?: { c: number }
}
}
const foo: Foo = {}
const num: ?string = foo?.a?.b?.c
ちゃんとエラー出た
Cannot assign foo?.a?.b?.c to num because number [1] is incompatible with string [2].
[1] 37│ b?: { c: number }
38│ }
39│ }
40│
41│ const foo: Foo = {}
[2] 42│ const num: ?string = foo?.a?.b?.c
43│
ただしoptional-chain 後の関数コールに対応していない
/* @flow */
type Foo = {
a?: {
b?: { c: number, d: Function }
}
}
const foo: Foo = {}
foo?.a?.b?.d()
Flow does not yet support method or property calls in optional chains.
39│ }
40│
41│ const foo: Foo = {}
42│ foo?.a?.b?.d()
43│
まてばどうにかなりそう。
この調子で https://github.com/tc39/proposal-pattern-matching と https://github.com/tc39/proposal-pipeline-operator もお願いします!!!!