You want to pass variable args to a function, like so:
const doSomething = (a: string, b?: string, c?: string): void => {}; 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); }) 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); }) 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); }) That's all!
Top comments (0)