![](/img/trans.png)
[英]How to declare variable of type A or B when one extends the other in Typescript
[英]Typescript bug? Function accepts Object with missing prop when defined to accept union of type A and B where B extends A
這可能是一個錯誤或者我不理解聯合類型。 看看這段代碼:
interface A {
a?: string;
b?: boolean;
}
interface B extends A{
x: boolean;
y: string;
}
function printCoord(pt: A | B) {
console.log("The coordinate's x value is " + pt.a);
console.log("The coordinate's y value is " + pt.b);
}
printCoord({ a: "asdf", b: true });
printCoord({a: "asdf", x: false});
最后一行不應該編譯,因為x
的存在強制類型B
,但y
缺失,所以它實際上應該是無效的。
union 類型用於聲明一種類型,它可以是其中之一(甚至兩者都是)。
例子:
interface A {
a1: string;
a2: string;
}
interface B {
b1: string;
b2: string;
}
const e1: A|B = {a1: "1", a2:"1"} // valid
const e2: A|B = {b1: "1", b2:"1"} // valid
const e3: A|B = {a1: "1", b1:"1"} // invalid
在您的示例中,您嘗試將{a: "asdf", x: false}
分配給A | B
A | B
。 因為類型A
幾乎可以接受任何東西(甚至{}
),所以{a: "asdf", x: false}
可以分配給A | B
A | B
。
它沒有拋出關於存在B
屬性的錯誤的原因是因為A | B
A | B
允許值是兩者的混合。 它必須至少是 A 或 B,但可以“激發”兩者兼而有之。
這就是為什么這也是有效的
printCoord({ a: "asdf" }); // valid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.