Advanced types
We have already learned about some basic types in the TypeScript language that we usually meet in other high-level languages. In this section, we’ll look at some advanced types that will help us during Angular development.
Partial
The Partial
type is used when we want to create an object from an interface but include some of its properties:
interface Hero {
name: string;
power: number;
}
const hero: Partial<Hero> = {
name: 'Boothstomper'
}
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, the preceding 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 the 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 already learned about generics and how they can 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 define the powers
property as an array of numbers or a key-value pair collection.
And that wraps up advanced types. As we learned, the TypeScript typing system is very flexible and allows us to combine types for more advanced scenarios.
In the following section, we will learn how to use modules with TypeScript.