mapped type use case in typescript
recently one of my friend asked me interesting question about typescript.
now he wants to create a new type which have same keys but with capital like below
here are my trials
Trial 1 ❌
using javascript map method ato capitalize the each key and then create new type based on it
but problem with this approach is that now we can assign any value to B type because B become string
type because using .map
method ( my guess )
Trial 2 ❌
tried using Mapped type and one interesting example with helps of template literal type and inbuilt Capitalize method was given on typescript official website so takeing that reference tried
Trial 3 ✅
now we use it simpler way using Capitalize
method
and this works exactly what we want
Note: this template literal type and Capitalize methods works with TypeScript v 4.1 and higher
Demo
typescript playground link for the same