当编译器无法自动推断时,如何在打字稿中强制执行函数调用签名



假设我有两个通过某种方式(假设远程过程调用(相关的函数,编译器无法推断。

//on the server
RandomFramework.declareHandler("foobarHandler", (foo: Foo, bar: Bar)=>{
//do stuff
});
//on the client 
RandomFramework.call("fooBarHandler", foo, baz); //baz is of type Baz instead of Bar

如何强制执行远程过程的呼叫签名?

>@jonsharpe是正确的。您需要定义如下类型:

type CustomFunction = (foo: Foo, bar: Bar) => void;

并且您的调用函数必须定义如下:

类型 自定义函数 = (foo: Foo, bar: bar( => void;

class RandomFramework {
public static call = <T extends (...args: any) => any>(key: string, ...args: Parameters<T>) => {
// do something
};
}

然后你称之为:

RandomFramework.call<CustomFunction>('fooBarHandler', foo, baz) // error because baz is not correct type

最新更新