使用联合类型分配的对象文字分配上的打字稿类型丢失

时间:2018-12-21 07:32:02

标签: typescript union-types

我期望下面的代码有错误,但是对于打字稿来说完全可以,您能告诉我为什么吗?

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是链接。

2 个答案:

答案 0 :(得分:1)

Typescript当前does not have精确类型的概念(对象文字存在例外,我将在最后解释)。换句话说,某个接口的每个对象都可以具有额外的属性(该属性在接口中不存在)。

因此该对象:

{
    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

答案 1 :(得分:0)

构造export type UnionType = Type1 | Type2;表示UnionType的实例是Type1Type2的实例。这并不一定意味着它们不能同时是两者的实例。

相关问题