Skip to main content

Readonly

Implement the built-in Readonly<T> generic without using it.

Constructs a type with all properties of T set to readonly, meaning the properties of the constructed type cannot be reassigned.

For example:

ts
interface Todo {
title: string
description: string
}
 
const todo: MyReadonly<Todo> = {
Cannot find name 'MyReadonly'. Did you mean 'Readonly'?2552Cannot find name 'MyReadonly'. Did you mean 'Readonly'?
title: "Hey",
description: "foobar"
}
 
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
ts
interface Todo {
title: string
description: string
}
 
const todo: MyReadonly<Todo> = {
Cannot find name 'MyReadonly'. Did you mean 'Readonly'?2552Cannot find name 'MyReadonly'. Did you mean 'Readonly'?
title: "Hey",
description: "foobar"
}
 
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
Solution ✅
ts
interface Todo {
title: string
description: string
}
 
type MyReadonly<T> = {readonly [P in keyof T]: T[P]}
 
const todo: MyReadonly<Todo> = {
title: "Hey",
description: "foobar"
}
 
todo.title = "Hello"
Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.
todo.description = "barFoo"
Cannot assign to 'description' because it is a read-only property.2540Cannot assign to 'description' because it is a read-only property.
ts
interface Todo {
title: string
description: string
}
 
type MyReadonly<T> = {readonly [P in keyof T]: T[P]}
 
const todo: MyReadonly<Todo> = {
title: "Hey",
description: "foobar"
}
 
todo.title = "Hello"
Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.
todo.description = "barFoo"
Cannot assign to 'description' because it is a read-only property.2540Cannot assign to 'description' because it is a read-only property.