Neok
Neok

Reputation: 770

Is generic record key possible?

Is it possible to return a Record with a generic key? Typing allows it, but implementation seems not possible.

function foo<K extends string>(key: K): Record<K, string> {
    return {
        [key]: "foo"
    }
}

Error:

Type '{ [x: string]: string; }' is not assignable to type 'Record<K, string>'.(2322)

Upvotes: 4

Views: 401

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42188

The quick fix is to assert that your returned object is of the right type.

function foo<K extends string>(key: K): Record<K, string> {
    return {
        [key]: "foo"
    } as Record<K, string>
}

The reason that this is necessary is because typescript acknowledges the possibility that the type K can be broader than just the literal string key (K could be string or union of string literals). If that's the case then your returned object would not actually fulfill the return type because it would not have a value for every key K.

It is currently not possible to state that a generic must be a single literal string, so some finessing with as is required.

Upvotes: 3

Related Questions