Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert interface into Function parameters in Typescript

What I wanted to know is if it is possible to use an interface to describe the parameters that need to be passed to a function. An example would be the following:

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

  function createPerson(name: string, age: number) {}

I'd like to use the Person interface as a reference for the createPerson parameters. So far, I've been using this:

function createPerson(name: Person['name'], age: Person['age']) {}

While it's better than nothing I still don't know if it is the best way for me to do this, since I still need to rewrite all parameter names. Is there a better option? Thanks in advance.

like image 721
Aylton Almeida Avatar asked Feb 26 '26 14:02

Aylton Almeida


1 Answers

I'm 99.9% sure there isn't a way to "spread" an interface's type definitions like that, not least because interfaces don't have an order while function parameters do.

You can do what you've shown in your question, or accept a Person object instead, either directly:

function createPerson(person: Person) { /* ... */ }

or with destructuring:

function createPerson({name, age}: Person) { /* ... */ }

Either way, you'd call it with an object, e.g.:

const createdPerson = createPerson({name: "Aylton Almeida", age: 20});
like image 116
T.J. Crowder Avatar answered Feb 28 '26 02:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!