1

I want to make a generic class that requires a template parameter that is an interface with only string keys.

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.

1 Answer 1

3

Record<string, > implies that it accepts any key, which you don't want.

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.

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't work, keyof T would not be restricted to string. sendEventData<TKey extends keyof T>(event: TKey, data: T[TKey]) { event.toLowerCase() // error, event is type string | number | symbol }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.