Ternary operator with values
In a wide range of programming languages, we can find if/then/else logic.
JavaScript provides a ternary1 operator that allows us to express this kind of
logic concisely. For example.
tsTryconstx = 16constisXNegative =x >= 0 ? "no" : "yes"
The general format of this expression in the regular JS/TS world, when used with values (as shown in the snippet above) is:
tscondition ? exprIfTrue : exprIfFalse
Conditional types
Conditional types allow for types to be expressed using a very similar (basically, the same) syntax
tsTryclassGrill {startGas () {}stopGas () {}}classOven {setTemperature (degrees : number) {}}typeCookingDevice <T > =T extends "grill" ?Grill :Oven letdevice1 :CookingDevice <"grill">letdevice2 :CookingDevice <"oven">
Let’s remove everything except for the conditional type:
tsTrytypeCookingDevice <T > =T extends "grill" ?Grill :Oven
Expressing conditions
On the right side of the = operator, you can see the same three parts
from our definition of a traditional value-based ternary operator
tscondition ? exprIfTrue : exprIfFalse
| part | expression |
|---|---|
| condition | T extends "grill" |
| exprIfTrue | Grill |
| exprIfFalse | Oven |
You probably notice the extends keyword in the condition. As of TypeScript v4.
3, is the only mechanism of expressing any kind of condition. You can think of
it kind of like a >= comparison
Quiz: Expressing conditions
Let’s study a few examples of extends scenarios and see if we can figure out
whether it will evaluate to true or false
| condition | |
|---|---|
| 1 | 64 extends number |
| 2 | number extends 64 |
| 3 | string[] extends any |
| 4 | string[] extends any[] |
| 5 | never extends any |
| 6 | any extends any |
| 7 | Date extends {new (...args: any[]): any } |
| 8 | (typeof Date) extends {new (...args: any[]): any } |
Click to reveal answers // SPOILER WARNING
tsTrytypeanswer_1 = 64 extends number ? true : falsetypeanswer_2 = number extends 64 ? true : falsetypeanswer_3 = string[] extends any ? true : falsetypeanswer_4 = string[] extends any[] ? true : falsetypeanswer_5 = never extends any ? true : falsetypeanswer_6 = any extends any ? true : falsetypeanswer_7 =Date extends { new (...args : any[]): any }? true: falsetypeanswer_8 = typeofDate extends { new (...args : any[]): any }? true: false
-
Definition of ternary: three-part
↩