javascript - 覆盖流对象类型中的单个字段类型的通用方法

标签 javascript types flowtype

给定一个类型

type X = {|
  a: number,
  b: number,
|};

我希望能够将其任何字段映射到另一种类型。例如,

type Y = {|
  a: string,
  b: number,
|};

type Y = {|
  a: number,
  b: any,
|};

我尝试了以下方法:

type Overwrite<O: Object, K: $Keys<O>, T> =
  {...O, [K]: T}

type X = {|
  a: number,
  b: number,
|};
type Y = Overwrite<X, 'a', string>;

const y: Y = {
  a: '12',
  b: 12,
}

乍一看似乎可行,但后来我意识到它也让 b 被覆盖,并且 a 仍然可以是 number

const y: Y = {
  a: 1,
  b: '1',
}

有什么办法可以实现我想要做的事情吗?

最佳答案

您可以使用对象扩展和精确类型进行覆盖:

type Overwrite<O, T> =
  {...O, ...T}

type X = {|
  a: number,
  b: number,
|};
type Y = Overwrite<X, {| a: string |}>;

const y: Y = {
  a: '12',
  b: 12,
}

// $ExpectError
const z: Y = {
  a: 1,
  b: '1',
}

关于javascript - 覆盖流对象类型中的单个字段类型的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45428990/

相关文章:

javascript - 具有更深路径的库的流 libdef

java - 如何在 java 中将 list<object> 转换为 list<MyType> ?

c# - 当前类型是接口(interface),无法构造。您是否缺少类型映射?

powershell - 如何在PowerShell中将字符串值转换为动态数据类型?

react-native - Flow 为新项目生成许多错误

redux - Redux reducer 默认语句中的奇怪类型空流语法

javascript - 动态边界更改不会在 'react-leaflet' 中产生任何影响

javascript - value() 或 constant() 可以在 AngularJS 中相互使用吗?

javascript - Django 模板 - 如果 object.val == true 则设置复选框被选中

javascript - 按属性值对对象数组进行排序