Typescript 类型脚本错误转换接口联合字段
这是产生错误的最小代码:Typescript 类型脚本错误转换接口联合字段,typescript,Typescript,这是产生错误的最小代码: interface A1 { type: "A1"; } interface A2 { type: "A2"; } type AU = A1 | A2; function foo(obj1: AU) { const obj2: AU = { type: obj1.type /* Error TS2322: Type '{ type: "A1" | "A2"; }' is not a
interface A1 {
type: "A1";
}
interface A2 {
type: "A2";
}
type AU = A1 | A2;
function foo(obj1: AU) {
const obj2: AU = {
type: obj1.type
/*
Error TS2322:
Type '{ type: "A1" | "A2"; }' is not assignable to type 'AU'.
Type '{ type: "A1" | "A2"; }' is not assignable to type 'A2'.
Types of property 'type' are incompatible.
Type '"A1" | "A2"' is not assignable to type '"A2"'.
Type '"A1"' is not assignable to type '"A2"'.
*/
};
}
这是打字错误吗?(我在他们的GitHub上以20889号发布了这篇文章)
还是我没有正确地使用这些工具?当从
obj2
声明中删除类型部分时-const obj2={type:obj1.type}
,obj2
的类型设置为{type:'A1'| A2'}
,代码编译正确
使用此语句,代码也可以正确编译,类型设置为AU
将obj2={type:obj1.type}设为AU
问题是,在将对象分配给obj2之前,它会尝试创建类型为“A1”|“A2”的对象
因此,{type:“A1”|“A2”}
实际上是一个暂时存在的未命名类型(您不能将其分配给AU)
通常的用例是A1和A2都有两个以上的属性,这些属性需要初始化,因此如果您要创建if-then-else代码,它将正确地将类型检测为{type:“A1”}或{type:“a”}
我非常怀疑微软是否会对此问题采取任何行动,因为这可能需要对解析器的工作方式进行更深入的重写。TypeScript团队将此标记为预期行为:
function foo(obj1: AU) {
// No errors:
if(obj1.type === 'A1') {
const obj2: AU = { type: obj1.type /* further attributes here*/ };
} else if(obj1.type === 'A2') {
const obj2: AU = { type: obj1.type /* further attributes here*/ };
}
}