[英]Typescript bug? Function accepts Object with missing prop when defined to accept union of type A and B where B extends A
This might be a bug or me not understanding union types.这可能是一个错误或者我不理解联合类型。 Take a look at this code:
看看这段代码:
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});
The last line should not compile, because the presence of x
enforces type B
, but y
is missing so it should actually be invalid.最后一行不应该编译,因为
x
的存在强制类型B
,但y
缺失,所以它实际上应该是无效的。
The union type is used to declare a type that is either one (or even both). union 类型用于声明一种类型,它可以是其中之一(甚至两者都是)。
example:例子:
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
In your example, you are trying to assign {a: "asdf", x: false}
to A | B
在您的示例中,您尝试将
{a: "asdf", x: false}
分配给A | B
A | B
. A | B
。 since type A
accepts pretty much anything (even {}
) then {a: "asdf", x: false}
can be assigned to A | B
因为类型
A
几乎可以接受任何东西(甚至{}
),所以{a: "asdf", x: false}
可以分配给A | B
A | B
. A | B
。
The reason it doesn't throw an error about the fact that there is a B
property there is because A | B
它没有抛出关于存在
B
属性的错误的原因是因为A | B
A | B
allows the value to be a mix of both. A | B
允许值是两者的混合。 It has to be at least A or B, but can "inspire" to be both.它必须至少是 A 或 B,但可以“激发”两者兼而有之。
that's why this is also valid这就是为什么这也是有效的
printCoord({ a: "asdf" }); // valid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.