TypeScript mapped type example
TypeScript Advance Types: Exercise-12 with Solution
Write a TypeScript program that defines a mapped type. It takes an object type as a parameter and makes all its properties read-only (immutable). Test the mapped type with an example object.
Sample Solution:
TypeScript Code:
// Define an example object type with properties
type Food = {
name: string;
price: number;
};
// Define a mapped type 'ReadOnly' that makes all properties read-only
type ReadOnly<T> = {
readonly [K in keyof T]: T[K];
};
// Create an example object of type 'Food'
const product: Food = {
name: "italian pizza",
price: 6, // In €
};
// Use the 'ReadOnly' mapped type to make the properties read-only
type ReadOnlyProduct = ReadOnly<Food>;
// Create an instance of the 'ReadOnlyProduct' type
const readOnlyFood: ReadOnlyFood = {
name: "American burger",
price: 4.79, // In US $
};
// Attempt to modify a property (will result in a TypeScript error)
// readOnlyProduct.name = "American burger"; // Error: Cannot assign to 'name' because it is a read-only property
// Print the 'readOnlyProduct' object
console.log(readOnlyProduct);
Explanations:
In the exercise above -
- First, we define an example object type called "Food" with two properties: 'name' and 'price'.
- Next, we define a mapped type called "ReadOnly" that takes a generic type parameter T. Within the mapped type, we use a mapped type transformation to iterate over the keys (K) of the input type (T). For each property, we use the readonly modifier to make it read-only.
- Create an instance of the "Item" type called "item".
- Use the ReadOnly mapped type to create a new type called "ReadOnlyProduct", which makes all properties read-only.
- Create an instance of the ReadOnlyFood type called 'readOnlyFood'. You can see that we've provided values for both properties, and they are now read-only.
- Finally we attempt to modify a property of "readOnlyFood", which results in a TypeScript error because read-only properties cannot be modified.
Output:
Uncaught ReferenceError: readOnlyProduct is not defined
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Mapped Type: Making properties optional.
Next: TypeScript conditional type example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/typescript-exercises/typescript-advance-types-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics