打字稿类型在使用联合类型的对象文字分配中丢失
typescript type is lost on an object literal assign using a union type
我预计以下代码会出错,但对于打字稿来说完全没问题,你能告诉我为什么吗?
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 是 link.
构造 export type UnionType = Type1 | Type2;
表示 UnionType
的实例是 Type1
或 Type2
的实例。这并不一定意味着它们不能是两者的实例。
Typescript 目前does not have 是精确类型 的概念(对象字面量除外,我会在最后解释)。换句话说,某些接口的每个对象都可以有额外的属性(接口中不存在)。
因此这个对象:
{
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
我预计以下代码会出错,但对于打字稿来说完全没问题,你能告诉我为什么吗?
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 是 link.
构造 export type UnionType = Type1 | Type2;
表示 UnionType
的实例是 Type1
或 Type2
的实例。这并不一定意味着它们不能是两者的实例。
Typescript 目前does not have 是精确类型 的概念(对象字面量除外,我会在最后解释)。换句话说,某些接口的每个对象都可以有额外的属性(接口中不存在)。
因此这个对象:
{
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