【发布时间】:2020-09-29 23:09:39
【问题描述】:
我想在自己的约束中使用泛型类型参数。在打字稿中完全有可能吗?
我的代码在这里:
type Config<T> = {
context: T;
};
type Hooks<T> = {
hooks: T;
};
type FunctionWithThis<T> = (this: T, ...args: any[]) => any;
type RemoveThis<T extends Record<string, FunctionWithThis<any>>> = {
[P in keyof T]: T[P] extends (...a: infer A) => infer R ? (...a:A) => R: never
}
const configure = <TContext extends Object,
THooks extends Record<string, FunctionWithThis<TContext & THooks>>> // problem here
(config: Config<TContext> & Hooks<THooks>) => {
const result = {
get data() { return config.context; }
};
Object.entries(config.hooks).forEach((action) => {
(result as any)[action[0]] = (...args: any[]) => action[1].call(config.context as any, ...args);
});
return result as { data: TContext; } & RemoveThis<THooks>;
};
const engine = configure({
context: {
foo: 12
},
hooks: {
log() {
console.log(this.foo); // this.foo is typed correctly here but I don't have access to another hooks
},
test(str: string) {
}
}
});
我正在尝试创建一个配置函数,用于执行具有预定义上下文的一组函数。
我已经设法创建了一个简单的演示版本,但现在我希望能够从另一个钩子中调用我的钩子。例如。我想配置我的test 挂钩来调用log 挂钩。
为了实现这一点,我尝试将联合类型作为通用参数传递给“FunctionWithThis”类型:
FunctionWithThis<TContext & THooks>
但不幸的是,它并没有给我我想要的东西:我的钩子仍然无法使用智能感知上下文。当泛型参数用作自身的约束时,似乎将其解析为unknown。
有办法克服吗?
实际上我还有更复杂的计划:我想为configure 函数和回调添加一个更通用的参数,并且还希望能够从钩子中调用回调,反之亦然。所以它看起来像这样:THooks extends Record<string, FunctionWithThis<TContext & THooks & TCallbacks>>> 其中TCallbacks 是THooks 之后的新通用参数
【问题讨论】:
标签: typescript typescript-generics