当我玩TypeScript的时候,我发现这个代码确实可以编译,但当然会抛出一个错误.
type Foo = {
kind: "foo",
foo: { foo: string };
}
type Bar = {
kind: "bar",
bar: { bar: string};
}
type Union = Foo | Bar;
function doSomething(fooOrBar: Union) {
fooOrBar.kind = "foo";
if(fooOrBar.kind === "foo")
console.log(fooOrBar.foo.foo);
}
doSomething({
kind: "bar",
bar: { bar: "bar" }
});
我想这是可能的,因为fooOrBar
包含Foo
和Bar
之间的共享属性,因此看起来像{kind: "foo" | "bar"}
,这确实允许赋值?
在我的情况下,我可以通过将kind
标记为readonly
来规避这个问题,但这感觉更像是一种变通方法,而不是我真正想要的.有没有什么方法可以明确地定义union仅仅是两种类型中的一种,从而禁止对kind的赋值?