A little background on the conditional type

TypeScript 2.8 brings the possibility of the conditional type. The conditional type creates a type by checking if an interface or an existing type extends a type or not. It uses the ternary operator (?:) to get the final type.

Using the conditional type with the dynamic number type

The following code shows a function on line 10 that takes a type T for a parameter. The generic T extends a union of two types defined on lines 1 and 5.

The function returns the object itself and puts the educational goal on the front instead. What is important is the return type on line 10: a type that uses the condition type. This type accepts the two union values and applies a condition that swaps the two types.

Line 16 returns a TypeB because TypeA was passed in parameter.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy