TypeScript Object Type Property Modifiers
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.
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.
Output:
Example 2: In this example, Dictionary is an object type with an index signature [word: string]: string. which means it can have keys of type string and values of type string. myDictionary is an instance of a Dictionary with three key-value pairs. You can access and modify values using dynamic keys within the specified type constraints.
type Dictionary = {
[word: string]: string;
};
const myDictionary: Dictionary = {
"apple": "a fruit",
"banana": "another fruit",
"car": "a vehicle",
};
// Outputs: "a fruit"
console.log(myDictionary["apple"]);