TypeScript: TypeScript Type Aliases (type)
Last updated: 2026-08-26
A type alias gives a type a name—it does not create a new type, but simply provides an existing type with a shorter, more meaningful name.
1. Basic Syntax of Type Aliases
(1) Naming Types
TYPESCRIPT
type ID = number;
type Name = string;
type Active = boolean;
let userId: ID = 42;
let userName: Name = "Charlie";
let isActive: Active = true;
(2) Object Type Aliases
TYPESCRIPT
type User = {
name: string;
age: number;
email: string;
};
let user: User = {
name: "Charlie",
age: 20,
email: "xiaoming@example.com"
};
💡 Both
type and interface can define the structure of an object— The syntax is slightly different (type uses =, while interface does not), but the effect is almost the same.
(3) Function Type Aliases
TYPESCRIPT
type GreetFunction = (name: string) => string;
let greet: GreetFunction = (name) => `Hello,${name}!`;
console.log(greet("Charlie")); // "Hello,Charlie!"
2. Union Type Aliases
type The most common use—naming union types, which greatly improves code readability:
(1) String Concatenation
TYPESCRIPT
type Status = "pending" | "active" | "completed" | "cancelled";
type Role = "admin" | "editor" | "viewer";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
let orderStatus: Status = "pending";
let userRole: Role = "admin";
let method: HttpMethod = "GET";
(2) Digital Convergence
TYPESCRIPT
type HttpStatus = 200 | 301 | 400 | 404 | 500;
type Bit = 0 | 1;
let code: HttpStatus = 200;
let flag: Bit = 1;
(3) Hybrid Combination
TYPESCRIPT
type Result = string | Error;
type Id = number | string | undefined;
let output: Result = "Success";
output = new Error("Failure"); // ✅ That's also legal
▶ Example: Describing API Responses Using Type Aliases
TYPESCRIPT
type ApiResponse<T> = {
status: number;
message: string;
data: T;
};
type User = {
id: number;
name: string;
email: string;
};
type UserResponse = ApiResponse<User>;
let response: UserResponse = {
status: 200,
message: "Achieve Success",
data: { id: 1, name: "Charlie", email: "xiao@example.com" }
};
console.log(`Status:${response.status}`);
console.log(`User:${response.data.name}`);
Output:
TEXT
📖 Display only
Status:200
User:Charlie
3. Cross-Type Aliases
The intersection type uses & to combine multiple types into a single one—the new type possesses all the properties of each of the original types:
(1) Basic Syntax
TYPESCRIPT
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
let person: Person = {
name: "Charlie",
age: 20
// Both must be present name and age
};
(2) Practical Applications—Combination Skills
TYPESCRIPT
type HasId = { id: number };
type Timestamped = { createdAt: Date; updatedAt: Date };
type SoftDeletable = { deletedAt: Date | null };
type Entity = HasId & Timestamped & SoftDeletable;
let article: Entity = {
id: 1,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null
};
(3) Cross-Conflict
When two types have properties with the same name but are of different types, the result of the intersection is never:
TYPESCRIPT
type A = { value: string };
type B = { value: number };
type C = A & B;
// C 's value The type is string & number = never
// No value can be both string and number
let c: C = { value: "" }; // ❌ You cannot string Assigned never
4. Tuple Type Aliases
TYPESCRIPT
type Point = [x: number, y: number];
type KeyValuePair = [key: string, value: number];
type RGB = [red: number, green: number, blue: number];
let coord: Point = [10, 20];
let entry: KeyValuePair = ["score", 95];
let color: RGB = [255, 128, 0];
// Deconstruction
let [x, y] = coord;
let [key, val] = entry;
5. Template Literal Types
TypeScript 4.1 introduced template literal types—string concatenation at the type level:
(1) Basic Syntax
TYPESCRIPT
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// Results:"onClick" | "onFocus" | "onBlur"
type CSSProperty = "margin" | "padding";
type CSSDirection = "top" | "right" | "bottom" | "left";
type CSSRule = `${CSSProperty}-${CSSDirection}`;
// Results:"margin-top" | "margin-right" | ... | "padding-left"
(2) Built-in string operation types
| Type | Function | Example |
|---|---|---|
Uppercase<S> |
All caps | Uppercase<"hello"> → "HELLO" |
Lowercase<S> |
all lowercase | Lowercase<"HELLO"> → "hello" |
Capitalize<S> |
Capitalize first letter | Capitalize<"hello"> → "Hello" |
Uncapitalize<S> |
lowercase initial | Uncapitalize<"Hello"> → "hello" |
▶ Example: A Type-Safe Event System
TYPESCRIPT
type EventType = "click" | "change" | "submit";
type HandlerName = `on${Capitalize<EventType>}`;
// "onClick" | "onChange" | "onSubmit"
interface EventHandlers {
onClick?: (x: number, y: number) => void;
onChange?: (value: string) => void;
onSubmit?: (data: FormData) => void;
}
// Usage——handler Type hints for names,I won't spell it wrong
let handlers: EventHandlers = {
onClick: (x, y) => console.log(`Click:(${x}, ${y})`),
onChange: (value) => console.log(`Value change:${value}`)
};
Output:
TEXT
📖 Display only
Click:(x, y)
Value change:value
6. A Comprehensive Comparison of Type and Interface
(1) Comparison of Capabilities
| Capability | type | interface |
|---|---|---|
| Object Type | ✅ type T = { ... } |
✅ interface T { ... } |
| Composite Type | ✅ type T = A | B |
❌ |
| Cross-type | ✅ type T = A & B |
Use extends instead |
| Aliases for Basic Types | ✅ type T = string |
❌ |
| Tuple Type | ✅ type T = [A, B] |
❌ |
| Template literal | ✅ type T = \...`` |
❌ |
| Merge Statements | ❌ | ✅ |
| class implements | ✅ | ✅ |
| extends | uses & | ✅ extends |
| Computed property key | ✅ [K in Keys] |
❌ |
(2) Select a Strategy
TEXT
📖 Display only
Required Features → Select
───────────────────────────────
Composite Types A | B → type
Aliases for Basic Types → type
Tuple [A, B] → type
Template Literal Types → type
Object Shape + Inheritance Required → interface
Object Shape + Statement Merger → interface
Simple Object Shapes → Either is fine,As long as the team is on the same page, that's fine.
▶ Example: Template Literal Types for Type-Safe Routes
TYPESCRIPT
type Method = "GET" | "POST" | "PUT" | "DELETE";
type Resource = "users" | "posts" | "comments";
type ApiEndpoint = `${Method} /api/${Resource}`;
// Valid values: "GET /api/users", "POST /api/posts", etc.
let endpoint: ApiEndpoint = "GET /api/users";
// Invalid — caught at compile time
// endpoint = "PATCH /api/users"; // ❌ PATCH not in Method
// endpoint = "GET /api/orders"; // ❌ orders not in Resource
type EventName = "click" | "focus";
type HandlerName = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus"
let handler: HandlerName = "onClick";
console.log(handler);
Output:
TEXT
📖 Display only
onClick
❓ FAQ
Q Can
type use extends for inheritance?A
type does not have an extends syntax, but you can achieve a similar effect using cross-types &—type Child = Parent & { extra: string }. The extends syntax in interface is clearer and can detect conflicts; when cross-types conflict, a never is generated instead of an error (the type simply becomes unavailable).Q Can a
type be implemented by a class?A Yes. As long as the
type defines an object type (excluding unions, primitive types, etc.), a class can implement it. class User implements UserType { ... } is completely valid.Q When must you use
type instead of interface?A There are three scenarios: (1) Union types—
interface cannot express A | B; (2) Tuple types—while you can use interface, it’s very awkward; (3) Template literal types—interface does not support them. In all other scenarios, the two are equivalent, and you can use either one.Q What are the practical uses of template literal types?
A They are primarily used for advanced type programming—such as automatically generating event names (onClick/onFocus), combining CSS properties (margin-top), and inferring routing path types. They aren’t commonly used in everyday development, but they are very powerful in defining types for frameworks and libraries. Beginners should just be aware of them.
📖 Summary
- type: Assigns an alias to an existing type; does not create a new type; syntax:
type Name = type - Union type aliases are the most common use of
type—they make complex union types readable and reusable. - Cross Type
A & BCombines all properties of multiple types; in case of a conflict, the result is "never" - Template literal types concatenate strings at the type level, in conjunction with built-in operations (such as Uppercase)
typeandinterfaceare equivalent in most cases; union types, tuples, and template literals must usetype
📝 Exercises
- Basic Problem (Difficulty ⭐): Define
StatusCode = 200 | 404 | 500usingtype, then defineApiResponse<T> = { code: StatusCode; data: T }. Create an instance ofApiResponse<string>and print it. - Advanced Problem (Difficulty ⭐⭐): Use the cross-type combinations
HasId,HasTimestamps, andHasAuditto define a completeEntitytype. Create an instance object and ensure that all properties are satisfied. - Challenge (Difficulty: ⭐⭐⭐): Define
CSSDirection = "top" | "right" | "bottom" | "left"using the template literal type, then generateMarginStyle = { [K inmargin-${CSSDirection}]: number }. Verify that the generated type includes properties such as marginTop and marginRight.