gpt4 book ai didi

javascript - 在流中扩展对象类型和覆盖属性

转载 作者:行者123 更新时间:2023-11-30 14:04:45 24 4
gpt4 key购买 nike

在 TypeScript 中,我可以执行以下操作:

interface MyObj {
a: 'foo' | 'bar'
}

interface MyExtObj extends Pick<MyObj, Exclude<keyof MyObj, 'a'>> {
a: MyObj['a'] | 'baz'
}

const test: MyExtObj = {
a: 'baz' // Works fine, as well as 'foo' and 'bar'
}

是否可以使用 Flow 对象类型来做到这一点?如果可以,怎么做?以下示例失败...

/* @flow */

type MyObj = {
a: 'foo' | 'bar'
}

type MyExtObj = MyObj & {
a: $PropertyType<MyObj, 'a'> | 'baz'
}

const test: MyExtObj = {
a: 'baz' // Cannot assign object literal blah blah ...
}

最佳答案

像这样?

/* @flow */

type MyObj = {|
a: 'foo' | 'bar'
|}

type MyExtObj = {|
...MyObj,
a: $PropertyType<MyObj, 'a'> | 'baz'
|}

const test: MyExtObj = {
a: 'baz' // Cannot assign object literal blah blah ...
}

你可以测试here

关于javascript - 在流中扩展对象类型和覆盖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55651830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com