首页 > 解决方案 > 打字稿类型在使用联合类型的对象文字分配上丢失

问题描述

我希望下面的代码会出错,但是打字稿完全没问题,你能告诉我为什么吗?

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' }],
};

是链接。

标签: typescriptunion-types

解决方案


Typescript 目前没有确切类型的概念(对象字面量有例外,我会在最后解释)。换句话说,某个接口的每个对象都可以有额外的属性(接口中不存在这些属性)。

因此这个对象:

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

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

关于对象文字的注释:打字稿确实为对象文字实现了精确类型的概念:

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

推荐阅读