A type alias in TypeScript is a name given to a type definition. It is used to simplify complex types and make them more readable. Type aliases can be used to define any type, including union types, intersection types, function types, and object types.
The syntax of a type alias looks like this:
type NewType = OriginalType;
This type definition means that we create a new type NewType
that is an alias for the OriginalType
. Here's an example:
type Employee = {
name: string;
age: number;
salary: number;
};
type Manager = Employee & {
department: string;
};
const john: Employee = { name: "John", age: 35, salary: 50000 };
const jane: Manager = { name: "Jane", age: 40, salary: 75000, department: "Sales" };
In the above example, we define a type alias Employee
for an object that has three properties: name
, age
, and salary
. We then define a type alias Manager
that extends the Employee
type by adding a department
property. We can use the Employee
and Manager
types to declare variables and TypeScript will check if the properties are of the correct type.
An interface in TypeScript is a type definition that describes the shape of an object. It is used to define the structure of an object and its properties, as well as the types of those properties. An interface can be used to define any type, including object types, function types, and class types.
The syntax of an interface looks like this:
interface NewType {
property1: Type1;
property2: Type2;
// ...
}
This type definition means that we create a new type NewType
that has properties property1
and property2
, with types Type1
and Type2
, respectively. Here's an example:
interface Employee {
name: string;
age: number;
salary: number;
}
interface Manager extends Employee {
department: string;
}
const john: Employee = { name: "John", age: 35, salary: 50000 };
const jane: Manager = { name: "Jane", age: 40, salary: 75000, department: "Sales" };
In the above example, we define an interface Employee
for an object that has three properties: name
, age
, and salary
. We then define an interface Manager
that extends the Employee
interface by adding a department
property. We can use the Employee
and Manager
interfaces to declare variables and TypeScript will check if the properties are of the correct type.
The main difference between a type alias and an interface in TypeScript is that a type alias can be used to define any type, including union types, intersection types, and function types, while an interface is used to define the structure of an object and its properties. Type aliases are more flexible than interfaces, but they are less expressive, because they cannot describe the shape of an object in the same way that an interface can.