Ask Your Question
3

In TypeScript, what is the method to define and invoke a function for a particular object type?

asked 2021-07-28 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-02-18 17:00:00 +0000

nofretete gravatar image

In TypeScript, you can define a function for a particular object type using an interface. Here is an example:

interface Person {
  name: string;
  age: number;
}

function sayHello(person: Person) {
  console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
}

const john: Person = {
  name: 'John',
  age: 30
};

sayHello(john);

In this example, we define an interface Person with properties name and age. We then define a function sayHello that takes a parameter of type Person, and logs a greeting to the console. Finally, we create an object john that conforms to the Person interface and call the sayHello function with john as the argument.

To invoke a function for a particular object type, you simply call the function with an object that matches the interface type.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-28 11:00:00 +0000

Seen: 8 times

Last updated: Feb 18 '23