13

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.

1
  • It's not an answer to the question you actually asked, but: Have you considered accepting an object? E.g., function createPerson(person: Person) (or function createPerson({name, age}: Person). Commented Oct 15, 2020 at 13:31

2 Answers 2

13

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});
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I was looking for this "spread" interface or anything like that. For me it's not a good option to accept the whole object but it's better than nothing. Tnks.
@AyltonAlmeida - I wanted this myself today and wondered...TypeScript is so incredibly flexible...maybe there's something...? So I pinged Titian Cernicova Dragomir, a TypeScipt expert, and he confirmed that there's no way to do it (at least, nothing you could rely on across TypeScript builds).
@AyltonAlmeida - FWIW, you can go the other way (slightly) via the Parameters utility type. So if you have (say) function foo(a: string, b: number): string;, then type FooParameters = Parameters<typeof foo> is the tuple type [a: string, b: number] (a labelled tuple, but you can't access tuple labels in the type system or code).
0

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) {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.