【发布时间】:2019-03-11 16:00:45
【问题描述】:
我正在尝试使用 Typescript Discriminated Union 在异步加载数据时模拟一个相当常见的场景:
type LoadingState = { isLoading: true; }
type SuccessState = { isLoading: false; isSuccess: true; }
type ErrorState = { isLoading: false; isSuccess: false; errorMessage: string; }
type State = LoadingState | SuccessState | ErrorState;
据我了解,这应该根据类型定义限制允许的值组合。但是,类型系统很乐意接受以下组合:
const testState: State = {
isLoading: true,
isSuccess: true,
errorMessage: "Error!"
}
我预计这里会出错。有什么我遗漏的或以某种方式滥用类型定义的吗?
【问题讨论】:
-
您是否启用了
suppressExcessPropertyErrors编译器选项? -
@cartant - 只是尝试将其设置为 true 和 false,但没有任何区别。
-
(自 2017 年以来,这一直是 TypeScript 中的一个未解决问题,请在此处查看进一步讨论:github.com/microsoft/TypeScript/issues/20863)
-
似乎问题已在 v3.5 中得到修复:typescriptlang.org/docs/handbook/release-notes/…
标签: typescript discriminated-union