简体   繁体   English

创建仅使用字符串键扩展接口的 TypeScript 泛型类型

[英]Create TypeScript generic type that extends interface with only string keys

I want to make a generic class that requires a template parameter that is an interface with only string keys.我想做一个通用的 class ,它需要一个模板参数,它是一个只有字符串键的接口。

I thought I could do something like我以为我可以做类似的事情

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

However, if I instantiate it like但是,如果我像这样实例化它

interface MyEvents {
    someEvent: { foo: string }
}

const instanace = new MyClass<MyEvents>();

I get a compilation error:我得到一个编译错误:

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

If I remove extends Record<string, object entirely, it compiles fine, but it doesn't restrict it to a map of string => object.如果我完全删除extends Record<string, object ,它编译得很好,但它不会将其限制为字符串的 map => object。

Record<string, > implies that it accepts any key, which you don't want. Record<string, >意味着它接受任何您不想要的键。

Instead, write T extends Record<string&keyof T, object> to restrict it to only keys that exist on the type, and that are also strings.相反,编写T extends Record<string&keyof T, object>以将其限制为仅存在于类型上的键,并且也是字符串。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM