0
0
Typescriptprogramming~5 mins

Mapped type with template literals in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a mapped type in TypeScript?
A mapped type creates a new type by transforming each property of an existing type. It loops over keys and applies changes, like making properties optional or readonly.
Click to reveal answer
beginner
What are template literal types in TypeScript?
Template literal types let you create new string types by combining or transforming other string types, similar to string templates but at the type level.
Click to reveal answer
intermediate
How do mapped types and template literal types work together?
You can use template literal types inside mapped types to create new property names by combining or modifying existing keys, like adding prefixes or suffixes.
Click to reveal answer
intermediate
Example: What does this mapped type do?
type PrefixedKeys<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] }
It creates a new type where each property name is prefixed with 'get' and capitalized, and the value is a function returning the original property type.
Click to reveal answer
beginner
Why use mapped types with template literals?
They help automate creating new types with modified keys, reducing repetitive code and improving type safety by generating consistent property names.
Click to reveal answer
What does the 'as' keyword do in a mapped type with template literals?
AIt filters keys from the original type
BIt changes the value types
CIt makes properties optional
DIt renames the keys using the template literal expression
Which TypeScript feature allows creating new string types by combining other string types?
ATemplate literal types
BUnion types
CIntersection types
DEnums
What does this mapped type produce?
type ReadonlyKeys<T> = { readonly [K in keyof T]: T[K] }
AA type with all properties readonly
BA type with all properties optional
CA type with keys renamed
DA type with function properties
In this example, what is the type of 'getName'?
type Person = { name: string };
type Getters = { [K in keyof Person as `get${Capitalize}`]: () => Person[K] };
A() => number
B() => string
Cstring
Dnumber
Why might you use mapped types with template literals in a real project?
ATo improve runtime performance
BTo write less code for loops
CTo automatically create related property names and types, reducing manual errors
DTo create CSS styles
Explain how mapped types and template literal types can be combined to transform property names in TypeScript.
Think about how you can rename keys by adding text before or after the original key.
You got /4 concepts.
    Describe a practical use case where mapped types with template literals improve your TypeScript code.
    Consider how you might create functions for each property automatically.
    You got /4 concepts.