简体   繁体   English

使用条件值定义typescript接口

[英]Define typescript interface with conditional values

Let's say I want to create an interface that looks like this: 假设我想创建一个如下所示的界面:

interface DataStatus<T> {
   isSuccess: boolean; 
   isError: boolean;
   data: T | undefined; 
}

And later on I'm going to be using this like: 后来我将使用它:

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
}

What I'd like to do add some conditions to the DataStatus interface with these rules: 我想做的是使用这些规则为DataStatus接口添加一些条件:

  • isSuccess and isError must be opposites isSuccessisError必须是对立的
  • data will have value T if isSuccess is true, and be undefined if isSuccess is false data有一定的价值T如果isSuccess是真实的,并undefined如果isSuccess是假的

Is this kind of thing possible with typescript? 打字稿有可能吗?

Yes, you can if you have a discriminated union. 是的,如果你有一个有区别的联盟,你可以。

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 is smart enough to figure out when hello.isSuccess is true inside that block where it knows it's true it will narrow down the type of hello to ISucessDataStatus instead of the union. Typescript很聪明,可以弄清楚何时hello.isSuccess在该块内是真的,它知道它是真的,它会将hello的类型缩小到ISucessDataStatus而不是union。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM