我想创建一个通用类,它需要一个模板参数,该参数是一个只有字符串键的接口。
我以为我可以做类似的事情
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>
以将其限制为仅存在于类型上的键,并且也是字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句