使用联合类型进行对象字面量分配时,打字稿类型丢失

2024-03-25

我预计以下代码会出现错误,但对于打字稿来说完全没问题,你能告诉我为什么吗?

export interface Type1 {
    command: number;
}

export interface Type2 {
    children: string;
}

export type UnionType = Type1 | Type2;

export const unionType: UnionType = {
    command: 34234,
    children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
};

Here https://www.typescriptlang.org/play/#src=export%20interface%20Type1%20%7B%0D%0A%20%20%20%20command%3A%20number%3B%0D%0A%7D%0D%0A%0D%0Aexport%20interface%20Type2%20%7B%0D%0A%20%20%20%20children%3A%20string%3B%0D%0A%7D%0D%0A%0D%0Aexport%20type%20UnionType%20%3D%20Type1%20%7C%20Type2%3B%0D%0A%0D%0Aexport%20const%20unionType%3A%20UnionType%20%3D%20%7B%0D%0A%20%20%20%20command%3A%2034234%2C%0D%0A%20%20%20%20children%3A%20%5B%7B%20foo%3A%20'qwerty'%20%7D%2C%20%7B%20asdf%3A%20'zxcv'%20%7D%5D%2C%0D%0A%7D%3B%0D%0A是链接。


当前打字稿不具有 https://github.com/Microsoft/TypeScript/issues/12936的一个概念确切的类型(对象文字有例外,我将在最后解释)。换句话说,某个接口的每个对象都可以具有额外的属性(接口中不存在这些属性)。

因此这个对象:

{
    command: 34234,
    children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
}

满足Type1接口,因为它具有它的所有属性(command) 属性,但它也满足Type2接口,因为它具有它的所有属性(children)也是如此。

关于对象字面量的注释: typescript 确实仅针对对象文字实现了精确类型的概念:

export const unionType: Type1 = {
    command: 34234,
    children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }], // oops, not allowed here
};

export const unionType: Type2 = {
    command: 34234, // oops, not allowed here
    children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
};

上面是演示对象文字的代码,下面是没有它们的代码:

const someVar = {
    command: 34234,
    children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }]
};

const: Type1 = someVar // ok, because assigning not an object literal but a variable
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用联合类型进行对象字面量分配时,打字稿类型丢失 的相关文章

随机推荐