typescript - 将记录转换为属性访问器
问题描述
我有一个函数,它使用 Object.defineProperty 在内部从某个定义生成父类。由于 defineProperty 不能很好地与 typescript 配合使用,因此函数的结果是从它的参数动态键入的。简化版如下所示:
type Class<T> = {new(): T}
// @ts-ignore
function createClass<T>(): Class<T> {
// creates class with correct parent
// adds properties to it's prototype using Object.defineProperty
}
class Foo extends createClass<Record<'bar', number>>() {
get bar() { // 'bar' is defined as a property in class 'Record<"bar", number>', but is overridden here in 'Foo' as an accessor.ts(2611)
return 2;
}
set bar(val) {
}
}
覆盖 bar getter 是个问题,因为打字稿不知道它实际上是访问器(它被键入为 Record),但我不知道如何将 getter-setter 对定义为一种类型(如果它是接口,它会起作用,但那不会' t 有动态键)。
TLDR:
我需要类似的东西type PropertyAccessor<K extends PropertyKey, V> = ...
来代替类似的Record<'bar', number>
东西:
type PropertyAccessor<K extends PropertyKey, V> = {
get [key: K](): V
set [key: K](val: V):void
}
但不幸的是,这不是有效的打字稿
解决方案
推荐阅读
- java - Spring Boot 中的 CORS 策略冲突
- r - 我可以将变量从全局文件导入 R 吗?
- mysql - 列“类别”的数据被截断
- javascript - Javascript 无法识别 require() 和导出
- sharepoint-online - Microsoft Teams:在自定义选项卡中为 Sharepoint 文档提供“在 Teams 中编辑”
- scala - 如何查询flink的可查询状态
- java - 可被所有小于 X 的数整除的最小可能数的最优算法
- php - 如何对数据库结果列表中的某些行进行颜色编码?
- c - 如何传递和返回指向结构数组的指针?
- spring - Spring Boot Actuator httptrace 如果作为查询参数发送,则以纯文本形式显示用户凭据