This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
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 ofT.- For each property
K, we declare a readonly property with the same name and typeT[K]. - This effectively sets all properties of
Ttoreadonly.
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.