men*_*fon 10 javascript typescript flowtype
这不会在"Try Flow"上编译:
/* @flow */
type A = { a: number, b: string};
type B = { a: string, b: string };
const x: A = { a:1, b:'2' };
const y: B = { ...x, a: x.a.toString() }
Run Code Online (Sandbox Code Playgroud)
错误是:
const y: B = { ...x, a: x.a.toString() }
^ Cannot assign object literal to `y` because number [1] is incompatible with string [2] in property `a`.
References:
3: type A = { a: number, b: string};
^ [1]
4: type B = { a: string, b: string };
^ [2]
Run Code Online (Sandbox Code Playgroud)
请注意,此代码适用于TypeScript(当我删除字段覆盖时,它无法按预期进行编译).
如何在不枚举原始对象的所有字段的情况下在Flow中实现相同的行为?
简短的回答:你不能这样做,这是Flow 中的一个“已知”错误。它是“已知的”,但我没有看到任何迹象表明有人实际上正在研究它。
你可以:
B.a为 的联盟number | string。声明一个映射函数,如下所示:
const mapfn = ({ a, ...rest }: A): B => ({ ...rest, a: a.toString() });
const x: A = { a: 1, b: '2' };
const y: B = mapfn(x);
Run Code Online (Sandbox Code Playgroud)编辑:看来你现在可以使用最新版本的 Flow 来做到这一点。有关详细信息,请参阅上述问题,他们已经修复了此错误。升级你的流程!