How to add types to a function that accepts object in TypeScript

June 6, 2024

To add types to a function that accepts an object in TypeScript.You can define an interface or a type for the object, and then use that interface or type in the function signature. Here’s an example to illustrate this:

1. Using an interface:

1interface User {
2 name: string;
3 age: number;
4 email?: string; // Optional property
5}
6
7function greetUser(user: User): void {
8 console.log(`Hello, ${user.name}. You are ${user.age} years old.`);
9 if (user.email) {
10 console.log(`Your email is ${user.email}`);
11 }
12}
13
14const user = { name: "John", age: 30 };
15greetUser(user);
16

2. Using a type alias:

1type User = {
2 name: string;
3 age: number;
4 email?: string; // Optional property
5};
6
7function greetUser(user: User): void {
8 console.log(`Hello, ${user.name}. You are ${user.age} years old.`);
9 if (user.email) {
10 console.log(`Your email is ${user.email}`);
11 }
12}
13
14const user = { name: "John", age: 30 };
15greetUser(user);
16

3. Inline type annotation:

1function greetUser(user: { name: string; age: number; email?: string }): void {
2 console.log(`Hello, ${user.name}. You are ${user.age} years old.`);
3 if (user.email) {
4 console.log(`Your email is ${user.email}`);
5 }
6}
7
8const user = { name: "John", age: 30 };
9greetUser(user);
10

In these examples, the greetUser function accepts an object of type User, which is defined to have name and age as required properties, and email as an optional property. You can adjust the type definition according to the properties your object needs to have.

Share this article