Readonly - TypeScript Challenge Explained

Sunday, March 12, 2023

My solution to the Readonly TypeScript Challenge as part of my journey to Understanding the TypeScript Challenges.

Given a type T, the utility should set the readonly keyword for all properties.

Solution

1type MyReadonly<T> = {
2  readonly [K in keyof T]: T[K]
3}

Explanation

  • { } return an object/record type
  • readonly set the "readonly" keyword for each item
  • [K in keyof T] loop over the keys
  • T[K] Select the value from the original type T for the each key K

Other posts


Tagged with: