【发布时间】:2019-12-10 14:51:53
【问题描述】:
我有一些类型,它们共享共同的道具,但这些道具有不同的对象。我想合并这些子对象,但它没有按我的预期工作。这是我的代码:
interface IFoo { foo: any };
interface IBarFnord { bar?: any; fnord?: any };
type Union = {test: IFoo } & {test: IBarFnord; otherTest?: IBarFnord };
const fails: Union = { test: { foo: null }};
const works: Union = { test: {foo: null, bar: null }};
const alsoWorks: Union = { test: {foo: null, fnord: null }};
对于const fails,我得到了错误:
类型 '{ foo: null; }' 与类型 'IBarFnord' 没有共同的属性。
这是真的。如果联合手段必须在两者中都有属性,那么它是有道理的。
我已经测试过这样做不是作为子道具,它工作正常:
type Union = {test: IFoo & IBarFnord };
const worksNow: Union = { test: { foo: null }};
const stillWorks: Union = { test: {foo: null, bar: null }};
无论如何,我如何告诉 Typescript 我想联合这些东西,但我不希望每个项目总是在联合的两边都有道具?
【问题讨论】:
-
您使用的是"union"这个词,但您使用的是
&,它表示intersection。那些是不同的;你真正想要哪一个?
标签: typescript types union-types