【问题标题】:How to define objects of mixed type in flow, then assign objects with a more definite type?如何在流中定义混合类型的对象,然后为对象分配更明确的类型?
【发布时间】: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 更改为booleannumber,并且在代码中的其他位置将引用视为{ foo: string }。您可以将更广泛的类型设为只读 flow.org/try/…

标签: javascript flowtype


【解决方案1】:

Aleksey 的建议对我有用 - 将我的对象中的字段标记为 read-only

export type Fields = { +[key: string]: string | number | boolean };

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2016-09-06
    • 2011-01-14
    相关资源
    最近更新 更多