Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.
In TypeScript, a type alias is a way to create a new name for a type.
Here's a simple example of type alias. You can read the rest of the tutorial to learn more.
Example
type Age = number;
const age: Age = 25;
console.log(age);
Here, type Age = number;
creates an alias Age
for the number
type. const myAge: Age = 30;
declares a variable myAge
with the Age
type, which is a number.
Syntax of Type Alias
You can create a type alias using the type
keyword, followed by the alias name and the type it represents.
type AliasName = Type;
For example,
type userName = string;
Here,
userName
is the alias name.string
is the type thatuserName
represents.
Alias for Object Types
You can use a type alias to define the structure of an object. For example,
type Person = {
name: string;
age: number;
};
const person: Person = {
name: "Alice",
age: 30,
};
Here, type Person = { name: string; age: number; };
creates a type alias Person
for an object with the name
and age
properties.
Then, we define a variable person with the Person
type.
This is especially useful when an object type is used multiple times, as it allows you to reuse the Person
type throughout your code.
Alias for Function Types
You can also use type aliases to define functions.
Let's define a type alias named Adder
for a function that takes two numbers (num1
and num2
) as input and returns a number:
type Adder = (num1: number, num2: number) => number;
Then, use the alias to define the function:
const add: Adder = (x, y) => x + y;
Here, we create a function called add()
and we tell TypeScript that add()
must match the Adder
type (i.e, it must take two numbers and return a number).
Finally, call the function:
console.log(add(5, 10)); // Output: 15
Here's the complete program to add two numbers using a type alias for the function:
// Define a type alias for a function that takes two numbers and returns a number
type Adder = (a: number, b: number) => number;
// Use the alias to type a function
const add: Adder = (x, y) => x + y;
console.log(add(5, 10)); // Output: 15
Frequently Asked Questions
Type aliases in TypeScript are not just for simple types or objects—you can also use them to represent union and intersection types.
Let's look at an example of a type alias used with a union type:
type ID = string | number;
let userId: ID;
userId = 101; // valid
userId = "abc123"; // valid
Here, ID
is a type alias for the union type string | number
. The variable userId
can now hold either a string or a number.