Use TypeScript's Mapped Types and Template Literal Types Together

Share this video with your friends

Send Tweet

In this final lesson, we're going to dive deep into a more complex example in which we combine mapped types, key remapping, template literal types, and indexed access types to statically type a highly dynamic JavaScript function in TypeScript.

Enrico
Enrico
~ 3 years ago

Why do we need the "TKey in string"? Why does TypeScript say it can be 'string | number | symbol' even though we said TObj extends Record<string, unknown>? Thanks for the course :)

Andrew Ross
Andrew Ross
~ 3 years ago

Enrico I think those are the primitive types (string | number | symbol) sans boolean, so I think by adding the intersection type TKey in string & keyof TObj... it denotes that we are filtering(?) TKey, otherwise of types string | number | symbol | keyof TObj, on the basis of whether a corresponding key is of type string or not. All non-string keys get 86'd (discarded) by incorporating this intersection.

Please correct me if my understanding is off

Andrew Ross
Andrew Ross
~ 3 years ago

Actually, after thinking on it, it seems that it is actually coercing the type of TKey to string, not necessarily filtering them