问题
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