Object types allow you to define the shape of objects by specifying the types of their properties. There are several ways to define object types, and we'll explore the most common approaches:
- 1. Object Literal:
- 2. Interface:
- 3. Optional Properties:
- 4. Readonly Properties:
- 5. Index Signatures:
- 6. Extending Interfaces:
- 7. Intersection Types:
- 8. Type Aliases:
You can directly specify the types of properties in an object literal.
let person: { name: string; age: number } = { name: "John", age: 30 };
Interfaces are a powerful way to define object types and provide a clear contract for the expected structure of an object.
interface Person {
name: string;
age: number;
}
let employee: Person = { name: "Alice", age: 25 };
You can mark properties as optional using the ?
syntax.
interface Car {
brand: string;
model?: string; // Optional property
}
let myCar: Car = { brand: "Toyota" };
You can mark properties as readonly using the readonly
keyword.
interface Point {
readonly x: number;
readonly y: number;
}
let coordinates: Point = { x: 1, y: 2 };
// coordinates.x = 3; // Error: Cannot assign to 'x' because it is a read-only property.
You can use index signatures to define objects with dynamic keys.
interface Dictionary {
[key: string]: number;
}
let ages: Dictionary = {
"John": 30,
"Alice": 25,
};
Interfaces can extend other interfaces, allowing you to build on existing definitions.
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
let mySquare: Square = { color: "red", sideLength: 5 };
You can combine multiple types using intersection types (&
).
type Name = { firstName: string };
type Age = { age: number };
let personInfo: Name & Age = { firstName: "John", age: 30 };
You can use type aliases to create reusable object types.
type Coordinates = { x: number; y: number };
let point: Coordinates = { x: 1, y: 2 };
These are some common ways to define object types in TypeScript. Choosing the right approach depends on the specific requirements of your application and the level of abstraction you want to achieve. Using interfaces is a recommended practice for defining object types in TypeScript because of their expressiveness and the ability to extend and reuse them.