DEV Community

Derek Nguyen
Derek Nguyen

Posted on

A spread argument must either have a tuple type or be passed to a rest parameter. ts(2556)

You want to pass variable args to a function, like so:

const doSomething = (a: string, b?: string, c?: string): void => {};
Enter fullscreen mode Exit fullscreen mode

However, TS didn't like it...

// não bom
const args = [['a', 'b', 'c'], ['a', 'b'], ['a']];
args.forEach((arg) => {

                // A spread argument must either
                // have a tuple type or be passed 
                // to a rest parameter. ts(2556)
                vvvvvv
    doSomething(...arg);
})
Enter fullscreen mode Exit fullscreen mode

The problem is that doSomething expects one to three arguments of type string, but arg is typed as string[]. We need to narrow the type down, to match the arguments of doSomething()

// bom
const properTypedArgs: [a: string, b?: string, c?: string][] = [['a', 'b', 'c'], ['a', 'b'], ['a']];
properTypedArgs.forEach((arg) => {
    doSomething(...arg);
})
Enter fullscreen mode Exit fullscreen mode

This works, but if you don't fancy re-typing the function's argument type defs or don't have it handy, TS utility type got you covered:

// ainda melhor
const properTypedArgs: Parameters<typeof doSomething>[] = [['a', 'b', 'c'], ['a', 'b'], ['a']];
properTypedArgs.forEach((arg) => {
    doSomething(...arg);
})
Enter fullscreen mode Exit fullscreen mode

That's all!

TS playground
Parameter<>
typeof

Top comments (0)