|
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:
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
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. Javascript
Output: Example 3: In this example, We define a Course object type with one optional property: price. We create two objects of type Course, Course1 with just the name property and Course2 with both name and price. We safely access the optional property price using conditional checks to ensure its existence before displaying its value or indicating its absence. Javascript
Output: Conclusion: In this article, we have seen Object Type Property Modifiers and it’s type with examples. They are used in property check in Typescript and it also make code more readable. Reference: https://www.typescriptlang.org/docs/handbook/2/objects.html#property-modifiers |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |