0

I have the following situation

type fnArgs = [string, number];

function test(a: string, b: number): void {}

const x: fnArgs = ['a', 2];

test(...x);

What I have is that the values passed to function test come from an array x (demo). The nice thing is that Typescript can figure out that the structure of the array matches the function signature in combination with the spread operator.

My quetion now is, can I use type fnArgs for the function signature as well? Because I have to define string, number twice.

2 Answers 2

1

Destructure your tuple inline:

function test(...[a, b]: fnArgs): void {}

You can also do this:

function test(...args: fnArgs): void {}
Sign up to request clarification or add additional context in comments.

Comments

1

Like this:

function test(a: fnArgs[0], b: fnArgs[1]): void {}
// −−−−−−−−−−−−−−^^^^^^^^^−−−−−^^^^^^^^^

Playground link

It's a bit repetitive, but at least if you change fnArgs' elements' types that change will be reflected in the function signature.


Just FWIW, you can do the same sort of thing when the type is an interface. For instance, if you have a function that retrieves something from somewhere by id:

interface Foo {
    id: string;
    // ...other fields here
}

function makeFoo(id: Foo["id"]): Foo {
    // ...
}

(Note: Foo.id won't work, it has to be the brackets form with quotes.)

If id gets changed from string to number, that change will be reflected in the function's signature.

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.