【发布时间】:2021-06-23 16:46:27
【问题描述】:
使用 Flow,我想为一个可以有任何键的对象定义一个类型,其值可以是字符串、数字或布尔值。
在其他地方我想定义多个可以充当子类型的更具体的类型,它们仍然符合这种类型,但定义了特定的键和值类型。
(我所说的“子类型”并不是指特定的流术语...)
export type Fields = { [key: string]: string | number | boolean };
export type MyFields = { foo: string };
const myFields: MyFields = { foo: 'bar' };
let fields: Fields = myFields;
为什么会导致以下错误?而且,有什么更好的方法来做到这一点?
Cannot assign `myFields` to `fields` because string is incompatible with number in property `foo`. Flow(InferError)
Cannot assign `myFields` to `fields` because string is incompatible with boolean in property `foo`. Flow(InferError)
【问题讨论】:
-
不合理,因为现在您可以将
foo更改为boolean或number,并且在代码中的其他位置将引用视为{ foo: string }。您可以将更广泛的类型设为只读 flow.org/try/…
标签: javascript flowtype