TypeScript – Union types, type guards and type aliases
All posts in TypeScript series:
- TypeScript – Union types, type guards and type aliases
- Intersection types in TypeScript
- Tuples in TypeScript
- Decorators with TypeScript
Union types
We can use union types in TypeScript to combine multiple types into one type:
let text: string | string[];
Variable text can now be either string or string array which can be pretty handy in some particular cases.
Use case in a function:
You can use union types with built-in types or your own classes / interfaces:
Type Guards in TypeScript
Technique used inside of function print is known as type guarding. We first checked if parameter text is of type ‘string’. If the text is “string” that value is returned. Therefore in remaining part of the function it was known to compiler that parameter text is of type ‘string[]’ – array of strings.
We can apply the same technique with custom types as well:
Type Aliases
You can define custom alias for already defined types:
type CustomString = string;
type CustomType = string | number;
As you would assume you can also use aliases for already defined custom types:
Generic type aliases
Lets say we have a generic interface:
interface GenericInterface<T1, T2>
{
x: T1;
y: T2;
}
Usage of generic interface:
let c: GenericInterface<number, string> = {
x: 3,
y: 'hey'
};
Lets make a generic type alias:
type InterfaceAlias<T> = GenericInterface<T, T>;
let d: InterfaceAlias<number> = {
x: 1,
y: 2
}
Summary
You can use union types to combine multiple types into one, this can be handy when you are moving existing JavaScript code to TypeScript. Therefore, you are probably dealing with code that has variables that are being assigned values of different types.
They can also be handy when you are using union types with your custom types.
We saw that you can set a new type that is union of any number of types. However, we can use type guarding technique to to eliminate or explicitly check variable’s type in a block.