typescript type is lost on an object literal assign using a union type

你离开我真会死。 提交于 2021-01-27 23:22:07

问题


I would expect an error from the following code, but for typescript is perfectly ok, can you tell me why?

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 is the link.


回答1:


Typescript currently does not have a concept of exact types (there is exception for object literals, I'll explain in the end). In other words, every object of some interface can have extra properties (which don't exist in the interface).

Hence this object:

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

satisfies Type1 interface because it has all of its properties (command) property but it also satisfies Type2 interface because it has all of its properties (children) as well.

A note on object literals: typescript does implement a concept of exact type only for object literals:

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

Above is the code which demonstrates object literals, and below is the code without them:

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

const: Type1 = someVar // ok, because assigning not an object literal but a variable



回答2:


The construct export type UnionType = Type1 | Type2; means that instances of UnionType are instances of Type1 or Type2. This does not necessarilly mean they cannot be instances of both.



来源:https://stackoverflow.com/questions/53880821/typescript-type-is-lost-on-an-object-literal-assign-using-a-union-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!