TypeScript
Objects
Object Types
const user: {
id: number;
name: string;
age?: number; // Optional property
} = {
id: 1,
name: "Pirate Dev",
};
?marks a property as optional: its type becomesnumber | undefined.readonlymarks a property that can't be reassigned after the object is created.
Type Aliases
You can isolate the type as follows:
type User = {
id: number;
name: string;
age?: number; // Optional property
};
const user: User = {
id: 1,
name: "Pirate Dev",
};
Interfaces
While type can be used to define the shape of any type (object, union, primitive), there is also interface that can define the shape of an object.
interface User {
id: number;
readonly name: string; // Readonly Property
age?: number; // Optional property
}
const user: User = {
id: 1,
name: "Pirate Dev",
};
user.name = "Someone else"; // Error: Cannot assign to 'name' because it is a read-only property
An interface can extend other interfaces:
interface Admin extends User {
role: string;
}
type vs interface
type | interface | |
|---|---|---|
| Object shapes | ✅ | ✅ |
| Unions, tuples, primitives | ✅ | ❌ |
| Extending | & (intersection) | extends |
| Declaring the same name twice | ❌ Error | ✅ Merged into one |
Union and Tuple types are supported only with
type, but not interface.A common rule of thumb: use interface for object shapes (especially public APIs that others may extend) and type for everything else.
Intersection Types
A & B combines types: the value must have all properties of both.
type HasId = { id: number };
type HasName = { name: string };
type Named = HasId & HasName;
const item: Named = { id: 1, name: "Pirate Dev" };
Index Signatures
When you don't know the property names in advance, describe the key and value types:
type Scores = {
[player: string]: number;
};
const scores: Scores = { alice: 10, bob: 7 };
Record<string, number> means the same thing (see Utility Types).
