In TypeScript, user-defined (or custom) types allow us to create new types from the composition of other types.
These types can represent complex data structures, unions of multiple types, or even behaviors.
Custom Data Types
Literal Data Types
Literal data types allow defining a specific set of values that a variable can take. For example:
let direction: "up" | "down" | "left" | "right";
direction = "up";
Enum Data Types
The enum data type allows defining a set of constants with more descriptive names. For example:
enum Direction {
Up = 1,
Down,
Left,
Right
}
let userDirection: Direction = Direction.Up;
Tuple Data Types
Tuples are a way to define an array with a fixed number of elements with specific data types. For example:
let employee: [string, number];
employee = ["John Doe", 35];
Object-Oriented Programming Types
Class Data Types
Classes are a way to define objects with methods and properties. They allow creating instances of objects and inheriting properties and methods from other classes. For example:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Animal is making a sound");
}
}
Interface Data Types
Interfaces are a way to define the structure of an object in TypeScript. They can contain properties, methods, and events. For example:
interface Person {
name: string;
age: number;
greet(): void;
}
Compound Types
Union Data Types
The union data type allows defining a variable that can accept several different data types. For example:
let age: number | string;
age = 25;
age = "25";
Intersection Data Types
The intersection data type allows combining two or more data types into one. For example:
type Admin = {
name: string;
isAdmin: boolean;
}
type Employee = {
name: string;
salary: number;
}
type AdminEmployee = Admin & Employee;