【发布时间】:2019-06-14 03:40:41
【问题描述】:
假设我想创建一个如下所示的界面:
interface DataStatus<T> {
isSuccess: boolean;
isError: boolean;
data: T | undefined;
}
稍后我将像这样使用它:
interface Foo {
id: string;
name: string;
}
function fetchData() : DataStatus<Foo> {
//implementation
}
const ds = fetchData();
if (ds.isSuccess) {
console.log(ds.data.name); //TS Warning - ds.data might be undefined
}
我想用这些规则为DataStatus 接口添加一些条件:
-
isSuccess和isError必须相反 -
如果
isSuccess为真,data的值为T,如果isSuccess为假,则为undefined
打字稿可以做这种事情吗?
【问题讨论】:
标签: typescript