Type aliases give a name to a type so you can reuse it easily. Inline types are written directly where you need them without a name.
0
0
Type alias vs inline types in Typescript
Introduction
When you want to reuse the same type in many places.
When you want to keep your code clean and easy to read.
When the type is simple and used only once, inline types are quick.
When you want to describe complex objects clearly with a name.
When you want to avoid repeating the same type details multiple times.
Syntax
Typescript
type TypeName = { property: Type; };
// Inline type example
function func(param: { property: Type }) { }Type aliases use the type keyword followed by a name and an assignment.
Inline types are written directly inside function parameters or variable declarations without a name.
Examples
This example creates a type alias
User and uses it to type a variable.Typescript
type User = {
name: string;
age: number;
};
const user: User = { name: "Alice", age: 30 };This example uses an inline type directly in the function parameter.
Typescript
function greet(user: { name: string; age: number }) { console.log(`Hello, ${user.name}`); }
Type alias for a point with x and y coordinates.
Typescript
type Point = { x: number; y: number };
const origin: Point = { x: 0, y: 0 };Inline type used directly when declaring a variable.
Typescript
const point: { x: number; y: number } = { x: 10, y: 20 };
Sample Program
This program shows how to use a type alias for a product and an inline type for a user object.
Typescript
type Product = {
id: number;
name: string;
price: number;
};
function printProduct(product: Product) {
console.log(`Product: ${product.name}, Price: $${product.price}`);
}
// Using type alias
const book: Product = { id: 1, name: "Book", price: 9.99 };
printProduct(book);
// Using inline type
function printUser(user: { id: number; username: string }) {
console.log(`User: ${user.username} (ID: ${user.id})`);
}
printUser({ id: 101, username: "john_doe" });OutputSuccess
Important Notes
Type aliases improve code readability and make it easier to update types in one place.
Inline types are good for quick, one-time use but can get messy if repeated often.
Both type aliases and inline types can describe objects, unions, intersections, and more.
Summary
Type aliases give a name to a type for reuse and clarity.
Inline types are written directly where needed without a name.
Use type aliases for repeated or complex types, inline types for simple, one-time use.