Horje
TypeScript Object Types

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.

Syntax

function 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

  • anyName is the name of the function.
  • a and b are properties passing as parameters with type string.

Example 1: Object with Required Properties

In this example, we defines a function printPerson that takes an anonymous object with name and marks properties.

JavaScript
function printPerson(person: { name: string; marks: number }) {
    console.log(`Name: ${person.name}, marks: ${person.marks}`);
}

// Anonymous object passed as an argument
printPerson({ name: "Akshit", marks: 30 });
printPerson({ name: "Nikita", marks: 25 });

Output:

Name: Akshit, marks: 30
Name: Nikita, marks: 25

Example 2: Object with Optional Properties

In 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.

JavaScript
function printPerson(person: { name: string; marks?: number }) {
    console.log(`Name: ${person.name}, marks: ${person.marks}`);
}

// Anonymous object passed as an argument
printPerson({ name: "Akshit", marks: 30 });
printPerson({ name: "Nikita"});

Output:

optional-object-type

Output

Example 3: Index Signatures

Index signatures allow defining object properties with dynamic keys.

JavaScript
function logFruits(fruits: { [key: string]: string }): void {
    for (const key in fruits) {
        console.log(`${key}: ${fruits[key]}`);
    }
}

logFruits({ apple: 'red', banana: 'yellow' });

Output:

apple: red
banana: yellow

Example 4: Type Inference

TypeScript can infer the type of an object based on its structure.

JavaScript
const person = { name: 'Alice', age: 30 };

function logPerson(person: { name: string; age: number }): void {
    console.log(`Name: ${person.name}, Age: ${person.age}`);
}

logPerson(person);

Output:

Name: Alice, Age: 30

Conclusion

This 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 Types

How do you define an object type in TypeScript?

Use an object literal or an interface to define the structure of an object, specifying property names and types.

How to pass an object as a function parameter in TypeScript?

Define the function parameter with an object type, specifying the expected properties and their types.

What are optional properties in TypeScript object types?

Properties that may or may not be present in an object. Defined with a ? after the property name.

How do index signatures work in TypeScript?

Index signatures allow defining properties with dynamic keys, using a [key: string]: type syntax.

Can TypeScript object types have methods?

Yes, object types can include methods, which are functions defined as properties within the object type.

What is type inference in TypeScript object types?

TypeScript can automatically infer the type of an object based on its structure, without explicit type annotations.




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Keyword Research - Definition, Importance, Elements & Steps in SEO Keyword Research - Definition, Importance, Elements & Steps in SEO
Local SEO | Definition, Importance, Steps & Tools Local SEO | Definition, Importance, Steps & Tools
Which Pages should you avoid Indexing for SEO? Which Pages should you avoid Indexing for SEO?
DigitalOcean Load Balancer Pricing | Analyzing the Cost and Benefits DigitalOcean Load Balancer Pricing | Analyzing the Cost and Benefits
React-Bootstrap Dropdowns Customization React-Bootstrap Dropdowns Customization

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12