首页 > 解决方案 > 创建仅使用字符串键扩展接口的 TypeScript 泛型类型

问题描述

我想创建一个需要模板参数的通用类,该模板参数是一个只有字符串键的接口。

我以为我可以做类似的事情

class MyClass<T extends Record<string, object>> {
    sendEventData<TKey extends keyof T>(event: TKey, data: T[TKey]) {
        // ...
    }
}

但是,如果我像这样实例化它

interface MyEvents {
    someEvent: { foo: string }
}

const instanace = new MyClass<MyEvents>();

我得到一个编译错误:

Type 'MyEvents' does not satisfy the constraint 'Record<string, object>'.
  Index signature is missing in type 'MyEvents'.

如果我完全删除extends Record<string, object,它编译得很好,但它不会将它限制为字符串 => 对象的映射。

标签: typescript

解决方案


Record<string, >意味着它接受您不想要的任何密钥。

相反,写入T extends Record<string&keyof T, object>将其限制为仅存在于类型上的键,并且也是字符串。

演示


推荐阅读