Objects are often easier to understand because property names provide context, while tuples rely on position.
Enums
JavaScript does not have built-in enums. TypeScript adds enums as a way to group related named constants together.
enum Response {
NO,
YES,
}
Key Points
Enum names and members are commonly capitalized.
Numeric enums start at 0 by default.
Subsequent values are automatically incremented.
enum Status {
PENDING,
APPROVED,
REJECTED,
}
You can also assign values explicitly.
enum Status {
PENDING = 10,
APPROVED,
REJECTED,
}
Enums and Databases
enum UserRole {
ADMIN = 'admin',
USER = 'user',
}
String Enums
enum UserRole {
ADMIN = 'admin',
USER = 'user',
}
Mixed Enums
enum Result {
SUCCESS = 1,
FAILURE = 'failed',
}
Enums vs Objects
const Response = {
NO: 0,
YES: 1,
} as const;
Interfaces
Interfaces are another way to describe the shape of an object in TypeScript. In many cases, interfaces and type aliases can be used interchangeably, but there are some important differences.
Basic Interface
interface User {
name: string;
age: number;
}
This is very similar to a type alias:
type User = {
name: string;
age: number;
};
Optional and Readonly Properties
Interfaces support optional properties using ? and readonly properties using the readonly keyword.