如何在流中定义混合类型的对象,然后分配更明确类型的对象?
How to define objects of mixed type in flow, then assign objects with a more definite type?
我想使用 Flow 为可以具有任何键的对象定义一个类型,其值可以包含字符串、数字或布尔值。
在其他地方我想定义多个更具体的类型,它们可以充当子类型,它们仍然符合这种类型,但定义特定的键和值类型。
(我所说的“子类型”并不是指特定的 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)
Aleksey 的建议对我有用——将对象中的字段标记为 read-only。
export type Fields = { +[key: string]: string | number | boolean };
我想使用 Flow 为可以具有任何键的对象定义一个类型,其值可以包含字符串、数字或布尔值。
在其他地方我想定义多个更具体的类型,它们可以充当子类型,它们仍然符合这种类型,但定义特定的键和值类型。
(我所说的“子类型”并不是指特定的 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)
Aleksey 的建议对我有用——将对象中的字段标记为 read-only。
export type Fields = { +[key: string]: string | number | boolean };