简体   繁体   English

将接口转换为 Typescript 中的函数参数

[英]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.我想使用Person接口作为createPerson参数的参考。 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.提前致谢。

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.我 99.9% 肯定没有办法像这样“传播”接口的类型定义,尤其是因为接口没有顺序而函数参数有。

You can do what you've shown in your question, or accept a Person object instead, either directly:您可以执行问题中显示的操作,也可以直接接受Person对象:

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

or with destructuring:或解构:

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

Either way, you'd call it with an object, eg:无论哪种方式,你都会用一个对象来调用它,例如:

const createdPerson = createPerson({name: "Aylton Almeida", age: 20});

You could make is so that function accepts 1 object as opposed to 2 separate args.您可以使函数接受 1 个对象,而不是 2 个单独的参数。 For example, you can do this.例如,您可以这样做。

function createPerson(p: Person) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM