This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.

AI solution for TypeScript puzzle on BFE.dev
3. implement Readonly<T>

Here's the implementation of MyReadonly<T>:

type MyReadonly<T> = {  readonly [K in keyof T]: T[K]};

Explanation:

  • MyReadonly<T> is a mapped type that iterates over all properties of T.
  • For each property K, we declare a readonly property with the same name and type T[K].
  • This effectively sets all properties of T to readonly.

We can use MyReadonly to create a readonly version of Foo:

type Foo = {  a: string}const a: Foo = {  a: 'BFE.dev',}a.a = 'bigfrontend.dev'// OKconst b: MyReadonly<Foo> = {  a: 'BFE.dev'}b.a = 'bigfrontend.dev'// Error: Cannot assign to 'a' because it is a read-only property.

Now, a.a = 'bigfrontend.dev' is allowed because a is of type Foo, but b.a = 'bigfrontend.dev' is not allowed because b is of type MyReadonly<Foo>, which has readonly properties.