Typescript keyof - 如何在声明中使用值?

Typescript keyof - how to use the value in a declaration?

我正在尝试使用 keyof 在现有 JS 库中强制执行类型安全(因此我无法重新定义任何函数调用)。 class 用 getset 函数包装了一个数据结构,像这样:

declare class Component<T> {

    set(data: T);
    get(key: keyof T);

}

到目前为止一切顺利!但现在我想添加一个观察者,使用我在 get 中使用的相同 keyof 功能。它的第二个参数是一个回调,它被赋予所提供的键的新旧值。我试过这样创建它:

type Callback<T, K extends keyof T> = (newValue: T[K], oldValue: T[K]) => void;

declare class Component<T> {
    observe(key: keyof T, cb: Callback<T, key>)
}

但是 TypeScript 拒绝我在 observe 函数中使用 key,说

cannot find name 'key'

我现在有什么办法可以绕过这个限制吗?我可以这样做:

observe<K extends keyof T>(key: keyof T, cb: Callback<T,K>)

它工作正常,但这意味着我的实际代码是:

thing.observe<"key">("key", (newValue, oldValue) => {})

这看起来很奇怪。

尝试使用这个:

type Callback<T, K extends keyof T> = (newValue: T[K], oldValue: T[K]) => void;

declare class Component<T> {
    observe<K extends keyof T>(key: K, cb: Callback<T, K>);
}

// example class
class XClass extends Component<{ name: string; value: number; }> { 
    testFn(): void { 
        // here the first argument needs to be a name of a T property
        // newValue and oldValue will be the same type of this property
        this.observe("name", (newValue, oldValue) => { });
    }
}