This is stretching my knowledge of TypeScrip and with an answer, I’d also appreciate a suggestion for a better question title.
I have a problem that when I introduce multiple levels of generic types, TypeScript type inference “forgets” the key type constraint:
type InnerMap = Record<string, unknown>;
type OuterMap<T extends InnerMap = InnerMap> = {
inner: T;
};
class Example<TMap extends OuterMap = OuterMap> {
method<K extends keyof TMap['inner']>(key: K) {
const a: string = key; // Error: Type 'string | number | symbol' is not assignable to type 'string'.
}
}
Link to a playground
In the example, it’s obvious that the K generic type can only be a string
(it’s a key of the InnerMap
which is a Record<string, unknown>
but for some reason, TS “loosens” the type constraint from string
to string | number | symbol
.
Does anyone know how to name this problem? Is it known?
I can “fix” it by telling TS that the generic type can only be a string
method<K extends keyof TMap['inner'] & string>(key: K) {
But that’s a bit hacky.