在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 ...
}
答案 0 :(得分:1)
喜欢吗?
/* @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
答案 1 :(得分:1)
如果您出于某些原因不想精确设置MyObj,请使用此also works:
/* @flow */
type MyObj = {
a: 'foo' | 'bar'
}
type MyExtObj = {|
...$Exact<MyObj>,
a: $PropertyType<MyObj, 'a'> | 'baz'
|}
const test: MyExtObj = {
a: 'baz' // Cannot assign object literal blah blah ...
}