typescript - 推断函数的参数类型
我想在 Typescript 中推断一个参数的类型,但到目前为止还不太顺利。
我有以下代码
// is it possible to find out the type of the payload parameter?
type Dispatch<T> = (prop: keyof T, payload?: any) => any;
class TestClass<T> {
obj: T;
dispatch: Dispatch<T> = (prop, payload) => {
const func = this.obj[prop];
return (func as any)(payload);
};
constructor(obj: T) {
this.obj = obj;
}
}
interface SomeFuncs {
foo(payload: string): string;
bar(payload: number): string;
}
const someFuncs: SomeFuncs = {
foo(payload) {
return 'Hello ' + payload;
},
bar(payload) {
const result = 10 + payload;
return 'Your result is ' + result;
},
};
const testClass = new TestClass(someFuncs);
const result = testClass.dispatch('bar', 'bla'); // I would like to get here an error because the payload for bar should be of type number
console.log(result);
是否有可能以某种方式推断 Dispatch<T> 类型中 payload 的类型?我尝试过使用在 2.8 中添加的 Parameters 功能,但仍然不知道如何解决它。
另一方面,键完全正常。因此,既然我有基础类型T和键,我认为应该有可能找出参数的类型。
答案#1
Dispatch 必须是一个泛型函数(不仅仅是泛型类型),才能捕获传入参数的实际类型,并使用它从 T 获取正确的参数
// is it possible to find out the type of the payload parameter
type Dispatch<T extends Record<keyof T, (...a: any[]) => any>> = <K extends keyof T>(prop: K, ...payload: Parameters<T[K]>) => any;
class TestClass<T extends Record<keyof T, (...a: any[]) => any>> {
obj: T;
dispatch: Dispatch<T> = (prop, ...payload) => {
const func = this.obj[prop];
return func(...payload);
};
constructor(obj: T) {
this.obj = obj;
}
}
interface SomeFuncs {
foo(payload: string): string;
bar(payload: number): string;
}
const someFuncs: SomeFuncs = {
foo(payload) {
return 'Hello ' + payload;
},
bar(payload) {
const result = 10 + payload;
return 'Your result is ' + result;
},
};
const testClass = new TestClass(someFuncs);
const result = testClass.dispatch('bar', 'bla'); // err
const result2 = testClass.dispatch('bar', 0); // ok
console.log(result);
注意:解决方案适用于 Typescript 3.0 及以上版本
