typescript - 创建仅使用字符串键扩展接口的 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
,它编译得很好,但它不会将它限制为字符串 => 对象的映射。
解决方案
Record<string, >
意味着它接受您不想要的任何密钥。
相反,写入T extends Record<string&keyof T, object>
将其限制为仅存在于类型上的键,并且也是字符串。
推荐阅读
- android - 如何在 BaseFragment() 中使用反射实现数据绑定
- netsuite - 通过子列表创建自定义记录时发送电子邮件
- firebase - 使用 Firebase 托管部署我的 Flutter Web 应用后出现错误
- typescript - Redux Saga 中的打字稿:类型 'void' 上不存在属性 'then'。TS2339
- javascript - 使用 Firebase Auth 通过小部件对用户进行身份验证
- security - 服务器到服务器通信中是否需要防伪令牌?
- sml - SML 中的自定义数据类型和函数
- python-3.x - Python 3:为什么我的“and”在“if”条件下充当“or”
- wpf - 不允许对 TextBox 进行双击鼠标操作
- android - 普通 NavigationDrawer 上的 RuntimeException