使用条件值定义打字稿界面

时间:2019-06-14 03:40:41

标签: typescript

假设我要创建一个看起来像这样的界面:

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界面中添加一些条件:

  • isSuccessisError必须相反
  • data如果T为true,则值为isSuccess;如果undefined为false,则值为isSuccess

打字稿可能发生这种情况吗?

1 个答案:

答案 0 :(得分:3)

是的,如果您有受歧视的工会,就可以。

interface ISuccessDataStatus<T> {
   isSuccess: true; 
   isError: false;
   data: T; 
}

interface IFailureDataStatus<T> {
   isSuccess: false; 
   isError: true;
   data: undefined; 
}


type PossibleStatus<T> = ISuccessDataStatus<T> | IFailureDataStatus<T>;


declare const hello: PossibleStatus<{ name: "john" }>

if (hello.isSuccess) {
    const whatType = hello.data; // T and not T | undefined
}

const whatType = hello; // PossibleDataStatus; (outside the if block)

Typescript足够聪明,可以确定何时在该块内知道hello.isSuccess为true的地方,它将把hello的类型缩小为ISucessDataStatus而不是联合。

相关问题