Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional types in TypeScript

I was wondering if I can have conditional types in TypeScript?

Currently I have the following interface:

interface ValidationResult {   isValid: boolean;   errorText?: string; } 

But I want to remove errorText, and only have it when isValid is false as a required property.

I wish I was able to write it as the following interface:

interface ValidationResult {   isValid: true; }  interface ValidationResult {   isValid: false;   errorText: string; } 

But as you know, it is not possible. So, what is your idea about this situation?

like image 337
Arman Avatar asked Dec 04 '19 09:12

Arman


People also ask

What are conditional types in TypeScript?

Conditional types help describe the relation between the types of inputs and outputs. When the type on the left of the extends is assignable to the one on the right, then you'll get the type in the first branch (the “true” branch); otherwise you'll get the type in the latter branch (the “false” branch).

What are the conditional types How do you create them?

Types that we create can have conditional logic, just like regular JavaScript code. The conditional type syntax uses the ternary operator that we are familiar with from JavaScript code. The extends keyword is used to define the condition. If T2 is within T1 then type A is used; otherwise, type B is used.

Does TypeScript offer type checking?

Code written in TypeScript is checked for errors before it is executed, during compile time.


1 Answers

One way to model this kind of logic is to use a union type, something like this

interface Valid {   isValid: true }  interface Invalid {   isValid: false   errorText: string }  type ValidationResult = Valid | Invalid  const validate = (n: number): ValidationResult => {   return n === 4 ? { isValid: true } : { isValid: false, errorText: "num is not 4" } } 

The compiler is then able to narrow the type down based on the boolean flag

const getErrorTextIfPresent = (r: ValidationResult): string | null => {   return r.isValid ? null : r.errorText } 
like image 96
bugs Avatar answered Oct 02 '22 18:10

bugs