首页 > 解决方案 > 将记录转换为属性访问器

问题描述

我有一个函数,它使用 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
 }

但不幸的是,这不是有效的打字稿

标签: typescript

解决方案


推荐阅读