If


Problem - On Github

This time we are creating a ternary type which will accept three types. If the first type is truthy it will resolve to the second type, otherwise it will resolve to the third type. This is similar to the conditional ternary operator <expression> ? <truthy> : <falsy> used in previous challenges.

The initial type provided is:

type If<C, T, F> = any

Solution

This must be one of the most simple challenges so far. We have previously used the conditional ternary statement to decide between two types so all we need to do is use it again.

In effect it is just if C is truthy then T else F. This is already what the conditional ternary does so just plug in the generic types, with a check for C being true.

type If<C, T, F> = C extends true ? T : F

Strict Type for C

We have passed the positive tests, but there is an additional expectation that C should be a true of false value. We can constrain the generic to extend boolean to enforce this with Typescript.

type If<C extends boolean, T, F> = C extends true ? T : F


What to read more? Check out more posts below!