2.8 Type aliases

TypeScript allow us to create alternative names for an existing type. These alternative names are known as type aliases.

Getting Ready

All you need to be able to use types aliases is an installation of TypeScript 2.0 or higher.

How to do it…

You can declare a type alias using the type reserved keyword followed by the name of the alias. You must assign a type as the value of the type alias:

type callback = (result: any) => void;

How it works…

The preceding line of code declared a type alias named callback. Callback is an alias for the type of a function which takes a variable of type any named result as its only argument and has no return type. You can then apply the type alias anywhere so instead of writing:

function doSomethingAsync(args: any, cb: (result: any) => void) {
  // …

You can write:

function doSomethingAsync(args: any, cb: callback) {
  // …

You can then invoke the function:

doSomethingAsync({ /* … */ }, (result: any) => {

If we visit GitHub and browse the TypeScript source code, we will be able to find some examples of type aliases like the following:

declare type ParameterDecorator = ( 
  target: Object, 
  propertyKey: string | symbol, 
  parameterIndex: number
) => void;

As you can see in the code preceding code snippet it is common to use type aliases to refer to complex function types. In general, you should try to avoid the in discriminated usage of type aliased as it could lead to maintainability issues. It is also recommended to create alias of types that you have not declared (native objects and third party libraries).

There’s more…

TypeScript version 1.8 introduces support for the usage of generics in type aliases:

type BaseReactClass<P, S> = reactWrapper.BaseReactClass<P, S>;

Please refer to the recipe about Generics and generic constraints in this chapter if you are not familiar with the usage of generics.

Source Code

Type aliases

See also

Refer to the next recipe about String literal types to learn how to combine union types and string literal types to create string enumerations.

Shiv Kushwaha