-
Book Overview & Buying
-
Table Of Contents
Clean Code with TypeScript
By :
Conditional types in TypeScript allow us to create types that adapt based on other types. They're like chameleons for our type system. This allows you to create more flexible and adaptable type definitions in your code.
The basic idea is this: you define a type with a condition. If the condition is true, the type resolves to one type; if the condition is false, it resolves to a different type.
The basic syntax of a conditional type is as follows:
type MyConditionalType<T> = T extends U ? X : Y;
Let's break down the code:
T: This is like a placeholder for any type of dataextends U: This checks whether T is the same type as U (or a subtype of U)X: If the check is true, the type becomes XY: If the check is false, the type becomes YConditional types are commonly used in scenarios where the resulting type depends on the characteristics of the input type.
Let's look at an example.
Let's say we have an Animal type that can be either 'cat' or 'dog':
type Animal = 'cat' | 'dog';
Now, we create a Sound type that represents the sound each animal makes. If it's a cat, the sound is 'meow'; if it's a dog, the sound is 'woof':
type Sound<T extends Animal> = T extends 'cat' ? 'meow' : 'woof';
Let's test our Sound type:
let sound1: Sound<'cat'>; // sound1 is 'meow' (because 'cat' extends 'cat')
let sound2: Sound<'dog'>; // sound2 is 'woof' (because 'dog' doesn't extend 'ca ')
In this example, Sound is a conditional type. It checks whether the Animal type (T) is 'cat'. If it is, the sound becomes 'meow'. Otherwise, it becomes 'woof'.
In the next section, we are going over the tsconfig.json file, what it is, and how it impacts your project.