简体   繁体   中英

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

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.

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

The construct export type UnionType = Type1 | Type2; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM