【问题标题】:How to create new Flow type having all properties of existing type but optional如何创建具有现有类型的所有属性但可选的新流类型
【发布时间】:2021-05-11 13:26:48
【问题描述】:

我有一个类型State,其中所有字段都是必需的:

type State = {
  title: string,
  items: [],
  isActive: boolean,
};

我需要创建一个所有属性都与State 相同但不是必需的新类型

type StateUpdater = {
  title?: string,
  items?: [],
  isActive?: boolean,
};

// ({title: 'hello'}: State) — INVALID
// ({title: 'hello'}: StateUpdater) — OK

如何实现类似于以下 Flow 伪代码?

type StateUpdater = State.mapKeyValue(() => typeKey?: typeValue)

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    您可以使用$Shape 实用程序:

    type State = {
      title: string,
      items: [],
      isActive: boolean,
    };
    
    type StateUpdater = $Shape<State>;
    

    $Shape 复制所提供类型的形状,但将每个字段标记为可选。

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多