TypeScript – Union types, type guards and type aliases

This entry is part 1 of 4 in the TypeScript series

All posts in TypeScript series:

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.



TypeScript Series Navigation: Previous post:
Next post: Intersection types in TypeScript >>



Ibrahim Šuta

Software Engineer, Mentor and Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js. Experienced in MeteorJS, Node.js, ASP.NET, Windows Forms and Web Forms as well.