
Ts Aliases And Interfaces in TypeScript
In TypeScript, Aliases and Interfaces are tools for defining the shape of data. Both serve similar purposes but have distinct use cases and capabilities. Here's an in-depth look at both:
1. Type Aliases
A Type Alias is a way to give a type a custom name. It can represent primitives, unions, tuples, or more complex structures.
Syntax:
// Primitive aliastype ID = string | number;// Object aliastype User = { id: ID; name: string; isAdmin?: boolean; // Optional property};// Using aliasesconst user: User = { id: 1, name: "John Doe" };
Key Features of Type Aliases:
- Can define unions and tuples:
type Response = "success" | "error";type Coordinates = [number, number];
- Can define function types:
type Add = (a: number, b: number) => number;
2. Interfaces
An Interface is used to define the structure of an object or class. It is more focused on defining objects and contracts.
Syntax:
interface InterfaceName { property: Type; method(param: Type): ReturnType;}
Example:
interface User { id: number; name: string; isAdmin?: boolean; // Optional property}// Using interfacesconst admin: User = { id: 1, name: "Admin", isAdmin: true };
Key Features of Interfaces:
- Inheritance: Interfaces can extend other interfaces.
interface Person { name: string;}interface Employee extends Person { employeeId: number;}
- Merging: Interfaces with the same name automatically merge.
interface Settings { theme: string;}interface Settings { layout: string;}// Merged:const config: Settings = { theme: "dark", layout: "grid" };
Comparison: Type Aliases vs. Interfaces
Feature | Type Alias | Interface |
---|---|---|
Usage | Suitable for primitives, unions, functions. | Best for defining object structures or contracts. |
Extensibility | Cannot be merged, but can use intersections. | Can be extended and merged. |
Union and Tuple Support | Supports unions and tuples. | Does not support unions or tuples directly. |
Declaration Merging | Not supported. | Supported. |
Complex Types | Suitable for advanced and hybrid types. | Less flexible for non-object types. |
Best Practices
- Use interfaces when defining the structure of objects or working with classes.
- Use type aliases when dealing with more complex types like unions, tuples, or function types.