typescript - 如何在 TypeScript 中使装饰器类型安全?
问题描述
例子:
class Parent {
parentMethod() {
// ...
}
}
@Hooks({
// Only methods from the `Child` class (including inherited methods) must be allowed here
childMethod: [/* ... */],
parentMethod: [/* ... */]
})
class Child extends Parent {
childMethod() {
// ...
}
}
装饰器将@Hooks()
对象作为参数。在此对象中,键是类中的方法名称Child
。如何使@Hooks()
装饰器类型安全?您能否提供一个包含类型的代码示例@Hooks()
?
解决方案
如果它对你有用,请检查它
interface ClassType<T> extends Function {
new (...args: any[]): T;
}
type MethodKeys<T> = ({
[K in keyof T]: T[K] extends Function ? K : never
})[keyof T]
type HooksOptions<T> = {
[K in MethodKeys<T>]: []
}
function Hooks<T>(_options: HooksOptions<T>) {
return function (ctor: ClassType<T>): ClassType<T> {
return ctor
}
}
class Parent {
parentMethod() {
// ...
}
}
@Hooks<Child>({
childMethod: [/* ... */],
parentMethod: [/* ... */]
})
class Child extends Parent {
childMethod() {
// ...
}
}
@Hooks("invalid-value") // error
class Child2 extends Parent {
childMethod() {
// ...
}
}
@Hooks<Child3>({
c: [], // error
childMethod: [/* ... */],
childMethod2: [/* ... */], // error
parentMethod: [/* ... */]
})
class Child3 extends Parent {
public c: string = ''
childMethod() {
// ...
}
}
推荐阅读
- r - 我的闪亮应用程序在我调用它时删除了我的 Markdown 的内容并且不保存为 pdf
- webpack - 如何在与 webpack 捆绑时将 SASS 变量转换为原生 CSS 变量?
- wiremock - 如何发送由标头值驱动的wiremock存根响应
- android - 发布新更新时未在 Play 商店中获取应用更新
- node.js - 加载资源失败:服务器响应状态为 404(未找到) ENOENT:没有这样的文件或目录,stat '/client/build/index.html'
- javascript - 如何在 bootstrap 5 popover setAttribute() 中添加 html 标签属性?
- c# - 设置 DataContext 后 WPF 依赖属性两种方式绑定不起作用
- python - 如何使用c语言访问zstd中字符串的压缩值?
- swagger - 仅从 Swagger 数据中过滤必填字段
- javascript - Web 索引数据库数据是否永久保留?