TypeScript Object Type Property Modifiers
Last Updated :
24 Apr, 2025
TypeScript Type Property Modifiers are used to specify each property in an object such as: the type, whether the property is optional, and whether the property can be written to.
TypeScript Object Type Property Modifiers:
- readonly Properties: An object type with readonly properties specifies that the properties of the object cannot be modified after their initial assignment, ensuring immutability and preventing accidental changes to the object's values.
- Index Signatures: It allows you to define object types with dynamic keys, where the keys can be of a specific type, and the corresponding values can be of another type. This is particularly useful when you want to work with objects that have properties that are not known at compile-time but follow a specific pattern.
- Optional Properties: An object type can have optional properties, which means that some properties of the object can be present or absent when creating objects of that type. Optional properties are denoted using the '?' modifier after the property name in the object type definition.
Example 1: In this example, Point is an object type with two read-only properties, x and y. When we attempt to modify the x property, TypeScript raises an error because it's read-only.
JavaScript
type Point = {
readonly x: number;
readonly y: number;
};
const point: Point = { x: 10, y: 20 };
console.log(point)
// Attempting to modify read-only properties
// will result in a TypeScript error
// point.x = 30; // Error: Cannot assign to
// 'x' because it is a read-only property.