In TypeScript, |
symbols are used to define union types (Union Types). A union type is an advanced type definition that allows you to define a type as one of many types. This is useful for dealing with variables that may have more than one type.
For example, suppose we have a function that takes one argument, which may be a number or a string. In JavaScript, we cannot explicitly specify the type of this parameter, but in TypeScript, we can use union types to do this:
function logInput(input: string | number) {
console.log(input);
}
In the above code, input
the type of the parameter is defined as string | number
, which means it can be a string or a number.
Union types are especially useful because TypeScript checks our code against all possible types in a union type. For example, consider the following code:
function getLength(input: string | number) {
return input.length;
}
This code results in an error because number
the type does not have length
a property. TypeScript's type checker knows input
that may be a number, so it won't let us try to access length
the property.
To handle this situation, we can use type assertions or type guards:
function getLength(input: string | number) {
if (typeof input === 'string') {
return input.length;
} else {
return input.toString().length;
}
}
In this example, we first check to see input
if is a string. If it is, we know it has length
the attribute, so we can safely access it. If input
is not a string, then we know it has to be a number, so we can convert it to a string and get its length.
Union types can also be used with other TypeScript features, such as type aliases and interfaces. For example, we can define a type alias that is a union of two interface types:
interface Cat {
type: 'cat';
breeds: string;
age: number;
}
interface Dog {
type: 'dog';
breeds: string;
age: number;
}
type Pet = Cat | Dog;
function printPet(pet: Pet) {
console.log(`Type: ${
pet.type}, Breeds: ${
pet.breeds}, Age: ${
pet.age}`);
}
In this example, Pet
the type is the union type of Cat
and Dog
. This means that a Pet
can be either one Cat
or one Dog
.
Overall, the notation in TypeScript |
provides a powerful way to deal with values that may have multiple types. By using union types, we can write more flexible code while still maintaining strong type safety.