Union types in TypeScript
Typescript allows us to express a type as a combination of two or more other types. This is known as a union type.
To create a union type, you can combine any types with the ( | ) pipe symbol like so:
function printSomething( something: string | number ) {
console.log(`something = ${something}`);
}
printSomething(7); // something = 7
printSomething('a string'); // something = a string
The printSomething function can accept either a string or a number type to indicate a union type.
Same can apply for a simple variable:
let myType : number | string = 'hello';
myType = 1;
*Note, using these types as union types aren’t very clean ways of writing code, but I guess this can be handy to know. Types should be specific to one type to avoid confusion and scaling properly with other developers. If using a Union type, probably the cleanest way to do it would be to create a type alias like so:
type StringOrNumber = string | number;
function printStringOrNumber(value: StringOrNumber) {
// ....
}
A type alias, similar to a typedef in Dart or C++. It is handy to describe a type and use the type for more sophisticated logic or components.