最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert interface into Function parameters in Typescript - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Oct 15, 2020 at 13:27 Aylton AlmeidaAylton Almeida 5691 gold badge5 silver badges19 bronze badges 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). – T.J. Crowder Commented Oct 15, 2020 at 13:31
Add a ment  | 

2 Answers 2

Reset to default 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});

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

发布评论

评论列表(0)

  1. 暂无评论