给出的是已区分的联合类型S1 | S2 | S3
:
type S1 = { d1: "foo"; }
type S2 = { d1: "bar"; isSuccess: true; }
type S3 = { d1: "baz"; isSuccess: false; errorMessage: string; }
type State = S1 | S2 | S3;
const testState: State = {
d1: "foo",
isSuccess: true, // no error, urgh..
errorMessage: "Error!" // no error, urgh..
// why no excess property check here?
}
我希望TS选择判别式d1
,因为它是同时存在于所有三个状态中的唯一属性,并且是有效的单例类型候选项。 isSuccess
在这里无法选择,因为它在S1
中不存在。
假设这种行为,为什么在给定isSuccess: true
值为d1
的情况下,我一输入"foo"
就不遵守多余的属性检查并且没有发出错误的原因?
这是我为了解问题而准备的test sample。