Home > Software engineering >  Conditionally branch on the Type Argument
Conditionally branch on the Type Argument

Time:05-30

Is it possible to conditionally branch type of function argument by the Type Argument?

In the following example, if T is 'str1', then arg is number. if T is 'str2', then arg is boolean.

type MyUnionType = 'str1' | 'str2'
function f<T extends MyUnionType>(arg: number | boolean) { ... }

CodePudding user response:

You can alternate types based on the generics used inside the argument list itself.

type MyUnionType = 'str1' | 'str2';
function f<T extends MyUnionType>(arg: T extends 'str1' ? number : boolean) {

}
f<'str1'>(5) // allowed
f<'str1'>(true) // not allowed
  • Related