YouTip LogoYouTip

Ts Type Alias

TypeScript type alias |

Type aliases are used to create aliases for existing types, making the code more concise and readable.

Through type aliases, you can define a short name for complex types, improving code maintainability.


Why Type Aliases Are Needed

When the same complex type is used multiple times in the code, writing out the full type each time becomes verbose.

Type aliases can define a concise name for complex types, making the code easier to read and maintain.

This is especially useful when working with union types, function types, tuples, and other complex types.

Concept Explanation: Type aliases are defined using the type keyword. They simply give an existing type a new name and do not create a new type.


Basic Usage

Use the type keyword to define aliases for types.

Example

// Type alias: Define alias for union type
// ID can be either string or number
type ID = string | number;

// Type alias: Define alias for object type
// Point represents a coordinate point
type Point = { x: number; y: number };

// Using type aliases
var userId: ID = "123";
var productId: ID = 456;

// Using Point type alias
var point: Point = { x: 10, y: 20 };

console.log("User ID: " + userId);
console.log("Product ID: " + productId);
console.log("Coordinate: " + JSON.stringify(point));

Output:

User ID: 123
Product ID: 456
Coordinate: {"x":10,"y":20}

Note: Type aliases just give types a new name; no actual code is generated after compilation. It's entirely used for type checking during development.


Interfaces vs Type Aliases

Type aliases and interfaces are very similar and can both be used to define object types, but there are some subtle differences.

Example

// Define object type using type alias
// type can define any kind of type, not just objects
type PersonType = {
    name: string;
    age: number;
};

// Define object type using interface
// Interfaces support declaration merging and can be implemented by classes
interface PersonInterface {
    name: string;
    age: number;
}

// Both can be used to declare variable types
var person1: PersonType = { name: "Alice", age: 25 };
var person2: PersonInterface = { name: "Bob", age: 30 };

console.log("PersonType: " + JSON.stringify(person1));
console.log("PersonInterface: " + JSON.stringify(person2));

Difference: Type can define any kind of type (union types, tuples, function types, etc.), while interfaces are mainly used for defining object types. Interfaces support declaration merging, whereas type aliases do not.


Type Aliases with Union Types

Type aliases are ideal for defining union types, making the code clearer.

Example

// Union type alias: Define possible values for state
// Status can only be one of these three string literals
type Status = "pending" | "success" | "error";

// Union type alias: Define multiple possible return types
// Result can be string, number, or boolean
type Result = string | number | boolean;

// Using union type alias
function getStatus(status: Status): void {
    console.log("Status: " + status);
}

getStatus("success");
getStatus("error");

// Using Result type
var result: Result = "hello";
result = 42;
console.log("Result: " + result);

Output:

Status: success
Status: error
Result: 42

Application Scenarios: Union type aliases are commonly used to define status codes, error types, API return values, and similar scenarios.


Type Aliases with Tuples

Type aliases can also be used to define tuple types.

Example

// Tuple type alias: Define coordinates
// Coordinate is a tuple containing two numbers
type Coordinate = [number, number];

// Tuple type alias: Define name and age
// NameAge is a tuple of string and number
type NameAge = [string, number];

// Using tuple type aliases
var coord: Coordinate = [10, 20];
var person: NameAge = ["Alice", 25];

console.log("Coordinate: " + coord);
console.log("Info: " + person + ", " + person);

Note: Tuple type aliases make tuple usage clearer, avoiding the need to write out the full tuple type every time.


Type Aliases with Functions

Type aliases can simplify function type declarations.

Example

// Function type alias: Define callback function type
// Callback accepts a string parameter and returns void
type Callback = (result: string) => void;

// Function type alias: Define math operation function type
// MathOperation accepts two number parameters and returns a number
type MathOperation = (a: number, b: number) => number;

// Using function type aliases
var add: MathOperation = function(a, b) { return a + b; };
var multiply: MathOperation = function(a, b) { return a * b; };

console.log("Addition: " + add(2, 3));
console.log("Multiplication: " + multiply(4, 5));

Output:

Addition: 5
Multiplication: 20

Advantage: Function type aliases make function type declarations more concise, especially when the same function signature is used multiple times.


Type Aliases with Generics

Type aliases can work with generics to create reusable type definitions.

Example

// Generic type alias: Define result type
// Result<T> is a generic type where T is the data type on success
type Result<T> = { success: boolean; data?: T; error?: string };

// Generic type alias: Define key-value pair type
// Pair<K, V> has two type parameters
type Pair<K, V> = { key: K; value: V };

// Using generic type aliases
var result: Result<string> = { success: true, data: "Hello" };
var pair: Pair<string, number> = { key: "age", value: 25 };

console.log("Result: " + JSON.stringify(result));
console.log("Key-Value Pair: " + JSON.stringify(pair));

Output:

Result: {"success":true,"data":"Hello"}
Key-Value Pair: {"key":"age","value":25}

Generic Advantage: Generic type aliases can adapt to different data types, increasing code reusability.


Type Aliases with Mapped Types

Type aliases can be combined with mapped types to create powerful type transformations.

Example

// Mapped type: Make all properties readonly
// Readonly<T> iterates through all properties of T and adds readonly
type Readonly<T> = { readonly : T };

// Mapped type: Make all properties optional
// Partial<T> iterates through all properties of T and adds ?
type Partial<T> = { ?: T };

// Define user interface
interface User {
    name: string;
    age: number;
}

// Using mapped type aliases
var readonlyUser: Readonly<User> = { name: "Alice", age: 25 };
// readonlyUser.name = "Bob"; // Error: Cannot modify readonly property

var partialUser: Partial<User> = { name: "Bob" };

console.log("Readonly User: " + JSON.stringify(readonlyUser));
console.log("Partial User: " + JSON.stringify(partialUser));

Tip: Mapped types are a powerful feature in TypeScript that can create new variations of existing types.


Important Notes

  • No Duplicate Definitions: The same type alias cannot be redefined (interfaces support declaration merging)
  • Compile-Time Only: Type aliases generate no code at runtime
  • Prioritize Readability: Don't overuse type aliases; clear and concise code is better

Best Practice: Use type aliases when types need to be reused or when type names are too long. For simple object types, choose between type and interface based on team conventions.


Summary

Type aliases are a very useful feature in TypeScript.

  • Basic Usage: Use the type keyword to define aliases for complex types
  • Union Types: Define combinations of multiple possible types
  • Function Types: Simplify function type declarations
  • Generics: Create reusable generic types
  • Mapped Types: Create new types based on existing ones

Suggestion: Reasonable use of type aliases can make code clearer, but avoid overusing themβ€”keeping code simple and readable is most important.

← Ts Abstract ClassTs Async Await β†’