TypeScript - Type Aliases



In TypeScript, type aliases is a way to define a type. It allows you to give a specific name to the type or define a custom type using the 'type' keyword. Basically, you can make some changes to the primitive and non-primitive data types and can define the custom data types using the type aliases.

Syntax

You can follow the syntax below to define type aliases in TypeScript.

type aliasName = Type;

In the above code, 'type' is a keyword. The 'AliasName' is a name of the type aliases. The 'Type' can be a primitive, non-primitive, or any custom data type.

Aliasing Primitive Types

The basic usage of the type alias of the aliasing the primitive types, meaning creating the copy of the primitive type. For example, in real-time applications, rather than using the string or number data type directly for the userID variable, we can create the userID alias and store the type in that to improve the code maintainability.

Example

In the code below, we have defined the 'UserID' type alias of number type. The 'user1' can variable contain only number value as its type is 'UserID'.

// Defining the type alias
type UserID = number;
// Defining the variable of type alias
let user1: UserID = 101;
console.log(user1);

On compiling, it will generate the following JavaScript code.

// Defining the variable of type alias
let user1 = 101;
console.log(user1);

The output is as follows –

101

Aliasing Union Types

Whenever you want to define a variable that can contain values of multiple types, you can use union types. For instance, if you are developing a function that accepts multiple types of input (like strings and numbers), using a type alias can make function signatures much cleaner. Otherwise, it can make the code complex if you repeat the union type throughout the code.

Example

In the code below, the 'StringOrNumber' type alias contains the union of the string and number. The logMessage() function accepts the string or numeric value as a parameter as the parameter type is 'StringOrNumber'.

Next, we executed the function after passing the string and number as an argument.

type StringOrNumber = string | number;
function logMessage(message: StringOrNumber): void {
    console.log(message);
}
logMessage("Hello");
logMessage(123);

On compiling, it will generate the following JavaScript code.

function logMessage(message) {
    console.log(message);
}
logMessage("Hello");
logMessage(123);

The output of the above code is as follows –

Hello
123

Aliasing Tuples

The tuple alias is used to define the structure of the fixed-size array, which can contain specific types of values in a particular order.

Example

In the code below, we have defined the 'RGBColor' tuple to store the RGB values of the color representation. In this tuple alias, all values are numeric.

type RGBColor = [number, number, number];
let red: RGBColor = [255, 0, 0];
console.log(`Red color: ${red}`);

On compiling, it will generate the following JavaScript code.

let red = [255, 0, 0];
console.log(`Red color: ${red}`);

The output of the above code is as follows –

Red color: 255,0,0

Aliasing Object Types

The object can have properties in the key-value format. Sometimes, you need to define multiple objects with the same structure, you can use the object type aliases. By creating the alias for the object type, you can reuse it.

Example

In the code below, we have defined the 'User' type which contains the id and name properties of the string type.

The 'user' object contains the string id and name.

// Defining the type alias for the User object
type User = {
    id: string;
    name: string;
};

// Defining the user object using the User type alias
let user: User = { id: "101", name: "Alice" };
console.log(user);

On compiling, it will generate the following JavaScript code.

// Defining the user object using the User type alias
let user = { id: "101", name: "Alice" };
console.log(user);

The output of the above code is as follows –

{ id: '101', name: 'Alice' }

Aliasing Function Types

Aliasing function types can be particularly useful when dealing with higher-order functions or callbacks, providing a clear contract for what functions are supposed to accept and return.

Example

In the code below, the 'GreeterFunction' defines the type of the function. It takes the string value as a parameter and returns the string value.

The 'greet' variable stores the function expression of type 'GreeterFunction'.

// Define a function type
type GreeterFunction = (name: string) => string;
// Define a function that matches the type
const greet: GreeterFunction = name => `Hello, ${name}!`;
console.log(greet("TypeScript"));

On compiling, it will generate the following JavaScript code.

// Define a function that matches the type
const greet = name => `Hello, ${name}!`;
console.log(greet("TypeScript"));

The output is as follows –

Hello, TypeScript!

Using Type Aliases with Generics

Generic types are used to create the custom types. It takes the type 'T' as a parameter, and creates a new type based on the type 'T'.

Example

In the code below, the 'Container' type accepts the type 'T' as a parameter, and defines the object property value of type 'T'.

After that, while using the 'Container' type, we pass the data type as an argument. For the 'numberContainer' variable, we have used the 'number' type, and for the 'stringContainer' variable, we have used the 'string' data type.

// Defining the generic type alias
type Container<T> = { value: T };

// Using the generic type alias
let numberContainer: Container<number> = { value: 123 };
let stringContainer: Container<string> = { value: "Hello World" };

console.log(numberContainer);  // Output: { value: 123 }
console.log(stringContainer);  // Output: { value: 'Hello World' }

On compiling, it will generate the following JavaScript code.

// Using the generic type alias
let numberContainer = { value: 123 };
let stringContainer = { value: "Hello World" };
console.log(numberContainer); // Output: { value: 123 }
console.log(stringContainer); // Output: { value: 'Hello World' }

The output of the above code s as follows –

{ value: 123 }
{ value: 'Hello World' }

Type aliases is the way to define custom types, also allowing to reuse of the complex type after defining once. It also helps in improving the code readability and minimizes the code complexity.

Advertisements