![]() |
TypeScript object types allow you to define the structure of objects with specific property types. They enable passing objects as function parameters, ensuring type safety and clarity. Optional properties can be included, providing flexibility in handling objects with varying properties and enhancing code robustness. Syntaxfunction anyName(fruit: { a: string; b: string }) {
console.log("The value of a is " + fruit.a);
console.log("The value of b is " + fruit.b);
}
anyName({ a: 'mango', b: 'apple' }); Parameters
Example 1: Object with Required PropertiesIn this example, we defines a function printPerson that takes an anonymous object with name and marks properties.
Output: Name: Akshit, marks: 30
Name: Nikita, marks: 25 Example 2: Object with Optional PropertiesIn this example, We defines a function printPerson that takes an anonymous object with optional marks property. It prints the object’s details. Two anonymous objects are passed and printed, one without marks.
Output: ![]() Output Example 3: Index SignaturesIndex signatures allow defining object properties with dynamic keys.
Output: apple: red
banana: yellow Example 4: Type InferenceTypeScript can infer the type of an object based on its structure.
Output: Name: Alice, Age: 30 ConclusionThis article explored object types in TypeScript, demonstrating how to use objects as function parameters, handle optional properties, use index signatures, and benefit from type inference. These practices enhance the flexibility, robustness, and maintainability of TypeScript code. FAQs- TypeScript Object TypesHow do you define an object type in TypeScript?
How to pass an object as a function parameter in TypeScript?
What are optional properties in TypeScript object types?
How do index signatures work in TypeScript?
Can TypeScript object types have methods?
What is type inference in TypeScript object types?
|
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |