Blog
JavaScript

Type Aliases in TypeScript: Creating Reusable Types

Simplify complex types with meaningful names

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name. Aliasing a primitive isn't very practical as it's easy using primitive types, however, it can be used for documentation purposes. Type aliasing is just giving another name for a type. let's demonstrate a few examples on type Aliasing.

Example 1: Creating a type alias

In this example we create a type alias named type_alias. The new type is a union of number, string, and boolean. if a new variable is declared with that type, the new variable can be given values that are only of types number, string, or boolean.

typescript

Output:

Here we try to give a variable of type function, typescript compiler raises an error.

typescript

Output:

Example 2: Implementing type alias in a function.

In this example, we will try implementing type alias in a function. We create a type alias called anotherType which is a union of number and string type. The function DisplayId can take arguments that are of type number or string. If any other type is given error is raised.

typescript

Output:

text

Example 3: String literals as type alias.

Instead of specifying types in union, we can use strings instead. A new type is created which is type alias of "yes"|"no". only "yes" or "no " strings can be given as values for the variables declared with otherType. when some other value is given as input typescript compiler raises error.

typescript

Output:

typescript compiler raises error:

After executing JavaScript file:

avatar

0 Comments

No comments

Leave a Reply

avatar

Recent Post

Related Topics

    Feeds

      Don't miss what's next 👋

      Enjoyed this content? Leave your email to get notified when we publish new insights, tutorials, and updates — no spam, ever.