简体   繁体   English

打字稿:如何根据同一接口内的布尔值排除可选性?

[英]Typescript: how to exclude optionality based on a boolean value within the same interface?

I have an interface and I am trying to implement this:我有一个接口,我正在尝试实现这个:

export interface Passenger {
       id: number,
       name: string,
       checkedIn: boolean,
       checkedInDate?: Date // <- How to make this optional only if checkedIn = false
}

why dont you just ignore the value of variable checkedInDate when checkedIn is true , something like thischeckedIn为true 时,为什么不忽略变量checkedInDate的值,像这样

if(!pessageobj.checkedIn) {
 pessageobj.checkedInDate = new Date();
} else {
pessageobj.checkedInDate =  some default date like min date;
}

You can't declare this in an interface.您不能在接口中声明它。 However you could implement this behaviour in a class:但是,您可以在类中实现此行为:

export class Passenger {
   id: number;
   name: string;
   checkedInDate?: Date;

   get checkedIn() {
      return this.checkedInDate != null;
  }       
 }

You can define Union Type :您可以定义联合类型

export type Passenger = {
    id: number,
    name: string,
    checkedIn: true,
    checkedInDate: Date
} | {
    id: number,
    name: string,
    checkedIn: false
    checkedInDate?: Date // you can just this field
}

A template parameter can specify the type of checkedIn with greater specificity (than just boolean ).模板参数可以更具体地指定checkedIn的类型(不仅仅是boolean )。 An intersection can then "add" either the optional or required version of checkedInDate .然后,交集可以“添加”可选版本或必需版本的checkedInDate

export type Passenger<A extends boolean> = {
    id: number;
    name: string;
    checkedIn: A;
} & (A extends false
    ? {
        checkedInDate?: Date;
    }
    : {
        checkedInDate: Date;
    });

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

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