Home > OS >  Creating a conditional Union Type - Typescript
Creating a conditional Union Type - Typescript

Time:11-03

I have an interface like this.

export interface IFormatOutputParameters {
  formatKey: number;
  numberType: 'General' | 'Percent' | '$';
  magnitudeTruncation: 0 | 1 | 2;
  decimalPlaces: 0 | 1 | 2;
}

I would like to add a new value to numberType called 'Date'. If the value of numberType is 'Date', both magnitudeTruncation and decimalPlaces should be null. If its the other three values, then it can be either 0, 1 or 2.

Please advice me on how to achieve this. I am looking into Type Guards and discriminating unions but not able to get what I am looking for. Thanks.

CodePudding user response:

You were already on the right track with discriminated unions. In this case, we can create an intersection of the formatKey and two unions. The two unions describe the valid states which you specified in the question.

type IFormatOutputParameters = {
  formatKey: number;
} & ({
  numberType: 'General' | 'Percent' | '$';
  magnitudeTruncation: 0 | 1 | 2;
  decimalPlaces: 0 | 1 | 2;
} | {
  numberType: 'Date',
  magnitudeTruncation: null;
  decimalPlaces: null;
})
  • Related