Conditional Types

A conditional type describes a conditional relationship between types.

Consider the following function for creating a label.

These overloads for createLabel describe a single function that makes a choice based on the types of its inputs. For each new type that createLabel can handle, the number of overloads will grow exponentially.

Instead, we can write a conditional type that maps string or number to the respective interface.

We can now use that conditional type to simplify the createLabel function.

Notice that we now have to explicitly use as to indicate the result of createLabel satisfies the result of the expression NameOrId<T>, since there isn't an efficient way for the TypeScript compiler to infer this automatically. This means you are still responsible for ensuring that the function correctly handles each input type, and always produces the output type that TypeScript is expecting.

Was this page helpful?