- Learning Angular
- Aristeidis Bampakos Pablo Deeleman
- 622字
- 2021-06-11 18:24:05
Advanced types
In the Types in Typescript 3.9 section, we learned about some of the basic types in the TypeScript language, which we usually meet in other high-level languages as well. In this section, we'll take a look at some of the advanced types that will help us in the development of an Angular application.
Partial
We use this type when we want to create an object from an interface but include some of its properties, not all of them:
interface Hero {
name: string;
power: number;
}
const hero: Partial<Hero> = {
name: 'Iron man'
}
In the preceding snippet, we can see that the hero object does not include power in its properties.
Record
Some languages, such as C#, have a reserved type when defining a key-value pair object or dictionary, as it is known. In TypeScript, there is no such thing. If we want to define such a type, we declare it as follows:
interface Hero {
powers: {
[key: string]: number
}
}
However, this syntax is not clear. In a real-world scenario, interfaces have many more properties. Alternatively, we can use the Record type to define the interface:
interface Hero {
powers: Record<string, number>
}
It defines key as a string, which is the name of the power in this case, and the value, which is the actual power factor, as a number.
Union
We've alrady learned about generics and how they help us when we want to mix types. A nice alternative, when we know what the possible types are, is the Union type:
interface Hero {
name: string;
powers: number[] | Record<string, number>;
}
In the preceding snippet, we defined the powers property as an array of numbers or a key-value pair collection, nothing more.
Nullable
We mentioned earlier, in the Types in TypeScript 3.9 section, that TypeScript contains two particular basic types, null and undefined, for assigning a variable to anything. We can leverage these types, along with the Union type, to indicate that a property is nullable:
interface Hero {
powers: number[] | null | undefined;
}
If we want to use the powers property in an object that's of the Hero type, we need to check for nullable values:
const hero: Hero = {
powers: [10, 20]
}
if (hero.powers !== null && hero.powers !== undefined) {
for (let i = 0; i < hero.powers.length; i++) {
}
}
Imagine what happens if we have many nullable properties. We need to type if-else statements for each one separately, which is a cumbersome process. A new feature recently that was added to TypeScript 3.9 comes to the rescue here, known as optional chaining. Essentially, it allows us to write our code so that TypeScript knows to stop execution automatically when it runs into a nullable value. To use it, we need to place the ? postfix in the nullable property, as follows:
for (let i = 0; i < hero.powers?.length; i++) {
}
Now, the if-else statement to check for nullable values is not needed anymore.