2021年2月3日星期三

Typescript: pass Parameters

In Typescript 4.1.x you can spread tuple types into functions as variadic arguments. However, I'm hitting an error when the tuple is derived from a generic type parameter and using the Parameters<T> utility type.

function foo(a: number, b: boolean, c: string) {    return 10;  }    foo(1, true, "baz") // 10 ✅    function bar(...params: Parameters<typeof foo>) {      return foo(...params)  }    bar(1, true, "baz") // 10 ✅    function bar2<F extends typeof foo>(...params: Parameters<F>) {    //  next line would work    //  return foo(params[0], params[1], params[2])      return foo(...params); // Fails 🛑    // Expected 3 arguments, but got 0 or more.ts(2556)    // index.ts(28, 14): An argument for 'a' was not provided.  }  

Is there a way to make this concept pass the type checker or is it not supported in typescript? Although it errors, it seems to work in the Typescript sandbox. See an example here.

Seems like I can get it to work with .apply(), but I'd love to know if there's another way.

function bar3<T extends typeof foo>(...params: Parameters<T>) {    return foo.apply(null, params);  }  
https://stackoverflow.com/questions/66036719/typescript-pass-parameterst-tuple-of-generic-function-type-parameter-as-varia February 04, 2021 at 06:34AM

没有评论:

发表评论