typescript 复用函数或类方法的参数类型

日常开发中,总会需要去封装一些三方库的功能进行使用。

在遇到简单类型的函数使用时,我们直接给我们功能函数添加上和被包装函数相同的类型即可。如:

    function A(args: number) {
        return libFun(args: number)
    }

但若是遇到复杂类型,如何直接去复用或者说继承被包装函数的类型?

1、复用函数类型

    function base(a: number, b: number, c: number): number
    function derived(add: string, ...base: Parameters<typeof base>): number
Extending another TypeScript function with additional arguments
Is it possible in TypeScript to define a function type and extend its argument list in another type (overloading function type?)? Let’s say I have this type: type BaseFunc = (a: string) =&gt; Promi...

2、复用类方法类型

type TypeOfClassMethod<T, M extends keyof T> = T[M] extends Function ? T[M] : never;
    
class MyClass
{
    private delegate: TypeOfClassMethod<MyClass, 'myMethod'>; // gets the type (boolean) => number;
    public myMethod( arg: boolean )
    {
        return 3.14;
    }
}

注:类可能带有泛型,自行补充上实际泛型类型即可,YourT例如:number .

TypeOfClassMethod<MyClass<YourT>, 'myMethod'>

Extending another TypeScript function with additional arguments
Is it possible in TypeScript to define a function type and extend its argument list in another type (overloading function type?)? Let’s say I have this type: type BaseFunc = (a: string) =&gt; Promi...
展示评论