在仍然推断参数的同时使用方法类型



用例

我有一个通过传入方法列表来构造的类,然后允许您通过该类调用这些方法(该类添加了一些额外的功能)。这些方法在调用时将类(Foo)绑定为它们的上下文。所以我有一个FooMethod类型

class Foo {
public constructor(methods) {}
}
const myMethod: FooMethod<number> = function(value: number): number {
return value
}
const myMethods = [myMethod]
const foo = new Foo(myMethods)
type FooMethod<T> = (this: typeof foo, ...args: any[]) => T
type MyMethodParameters = Parameters<typeof myMethod> // any[]
<标题>

通过将FooMethod<number>类型添加到myMethodconst。我不能再通过执行Parameters<typeof myMethod>

来获得函数的参数类型<标题>

是否有一种方法可以让FooMethod类型仍然推断参数?我希望能够在执行Parameters<typeof myMethod>时仍然得到[number]

这是因为在您的type FooMethod<T>中,您将rest参数声明为any[]。

您可以将参数作为泛型添加到您的类型:

type FooMethodNew<Args extends any[], ReturnValue> = (this: typeof foo, ...args: Args) => ReturnValue

但在实践中可能是多余的/冗长的

const myMethodNew: FooMethodNew<[value: number], number> = function(value: number): number {...}
相反,您可以使用辅助函数来帮助利用函数 的推理能力。
const fooMethodBuilder = <Args extends any[], ReturnValue>(func: FooMethodNew<Args, ReturnValue>) {
return func
}
const myMethodBuilt = fooMethodBuilder(function(value: number): number {
console.log(this)
return value
})
type MyMethodParameters3 = Parameters<typeof myMethodBuilt> // [value: number]

在TS Playground上查看

最新更新