A type alias is a way to give a name to any type. It can represent primitive types, union types, intersection types, tuple types, and more. Type aliases are defined using the type
keyword.
// Primitive type alias
type MyString = string;
// Union type alias
type StringOrNumber = string | number;
// Intersection type alias
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type PersonEmployee = Person & Employee;
An interface is a contract that defines a shape of an object. It describes the properties and their types that an object must have. Interfaces are defined using the interface
keyword.
interface Point {
x: number;
y: number;
}
|
) and intersection (&
) operators.type Admin = {
role: 'admin';
permissions: string[];
};
type User = {
role: 'user';
id: number;
};
type AdminOrUser = Admin | User;
type Direction = 'north' | 'south' | 'east' | 'west';
interface UserProfile {
name: string;
age: number;
email: string;
}
const user: UserProfile = {
name: 'John Doe',
age: 30,
email: '[email protected]'
};
interface Animal {
makeSound(): void;
}
class Dog implements Animal {
makeSound() {
console.log('Woof!');
}
}
type PositiveNumber = number & { __positive: never };
function square(num: PositiveNumber): PositiveNumber {
return (num * num) as PositiveNumber;
}
type NumericArray = number[];
type StringOrNumericArray = string[] | NumericArray;
interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
area() {
return Math.PI * this.radius * this.radius;
}
}
class Square implements Shape {
constructor(private side: number) {}
area() {
return this.side * this.side;
}
}
interface BaseUser {
name: string;
}
interface ExtendedUser extends BaseUser {
age: number;
}
type AnimalType = 'dog' | 'cat';
interface Dog {
type: 'dog';
bark(): void;
}
interface Cat {
type: 'cat';
meow(): void;
}
type Animal = Dog | Cat;
function isDog(animal: Animal): animal is Dog {
return animal.type === 'dog';
}
Type aliases and interfaces in TypeScript are both valuable tools for defining custom types. Type aliases are more flexible and suitable for creating complex types, working with primitives and literals, and using in type guards. Interfaces, on the other hand, are ideal for defining object shapes, sharing type definitions, and enforcing contracts in classes. By understanding their differences and following best practices, developers can write more robust and maintainable TypeScript code.