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)
(orfunction createPerson({name, age}: Person)
. – T.J. Crowder Commented Oct 15, 2020 at 13:31
2 Answers
Reset to default 13I'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) {}