【问题标题】:Get parameters from generic functions' declaration - TypeScript 3.3从泛型函数的声明中获取参数 - TypeScript 3.3
【发布时间】:2019-08-13 17:36:26
【问题描述】:
我不知道如何获取接口中声明的函数的参数类型。我需要对它们进行适当的类型检查。可能我需要使用:TypeScript 版本中的参数类:3.3:https://github.com/Microsoft/TypeScript/blob/v3.3.1/lib/lib.es5.d.ts#L1471-L1474 但我不知道如何使用它。
interface MyFunctions {
FIRST_FUNCTION: () => void;
SECOND_FUNCTION: (string, number) => void;
}
class Params<Functions> {
private functions: Map<keyof Functions, Set<Functions[keyof Functions]>> = new Map();
// some other functions...
public boom<K extends keyof Functions>(func: K, ...args: ???? /* here I don't know how to define type*/ ) {
this.functions.get(func)(args);
}
}
【问题讨论】:
标签:
typescript
generics
parameters
keyof
【解决方案1】:
以下是我解决您问题的方法,并指出我必须清理很多东西并猜测您在做什么:
interface MyFunctions {
FIRST_FUNCTION: () => void;
SECOND_FUNCTION: (x: string, y: number) => void; // FIXED
}
// constrain Functions to a type holding only function properties
class Params<Functions extends Record<keyof Functions, (...args: any[]) => any>> {
private functions: Map<keyof Functions, Set<Functions[keyof Functions]>> = new Map();
// use Parameters as requested
public boom<K extends keyof Functions>(func: K, ...args: Parameters<Functions[K]>) {
// assert that it returns a set of the right kind of function
const funcSet = (this.functions.get(func) || new Set()) as Set<Functions[K]>;
// okay, and remember to use spread
funcSet.forEach(f => f(...args));
}
}
new Params<{a: string}>(); // error, string is not a function
new Params<MyFunctions>().boom("FIRST_FUNCTION"); // okay
new Params<MyFunctions>().boom("SECOND_FUNCTION", "a", 1); // okay
与您的问题有关的部分:
我将constrained 泛型Functions 类型为Record<keyof Functions, (...args: any[]) => any>,以便编译器知道Functions 的所有属性都必须是函数。这将阻止您致电new Params<{a: string}>()。
我已将args 其余参数键入为Parameters<Functions[K]>,其中Functions[K] looks up 是Functions 的属性,键为K。由于泛型约束,编译器知道Functions[K] 必须是函数类型,因此很高兴允许您将其传递给Parameters<> 并返回参数元组。
我重新编写了boom() 的实现,以便对我更有意义。我需要做一个type assertion 来让编译器相信this.functions.get(func) 的结果实际上是一组Functions[typeof func],而不是一组更广泛的Functions[keyof Functions]。我调用了获得的Set 的每个函数元素,在参数上使用spread syntax。如果这些假设是错误的,希望它们仍能引导您朝着有用的方向前进。
希望有所帮助;祝你好运!