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

在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 ...

}


梦里花落0921
浏览 146回答 2
2回答

偶然的你

像这样?/* @flow */type MyObj = {|&nbsp; &nbsp; a: 'foo' | 'bar'|}type MyExtObj = {|&nbsp; &nbsp; ...MyObj,&nbsp; &nbsp; a: $PropertyType<MyObj, 'a'> | 'baz'|}const test: MyExtObj = {&nbsp; &nbsp; a: 'baz' // Cannot assign object literal blah blah ...}

阿波罗的战车

如果由于某些原因您不想精确设置MyObj,这也可以使用:/* @flow */type MyObj = {&nbsp; &nbsp; a: 'foo' | 'bar'}type MyExtObj = {|&nbsp; &nbsp; ...$Exact<MyObj>,&nbsp; &nbsp; a: $PropertyType<MyObj, 'a'> | 'baz'|}const test: MyExtObj = {&nbsp; &nbsp; a: 'baz' // Cannot assign object literal blah blah ...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript