Convert interface into Function parameters in Typescript

Viewed 1642

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.

2 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});

You could make is so that function accepts 1 object as opposed to 2 separate args. For example, you can do this.

function createPerson(p: Person) {}

Related