Skip to main content

Readonly

introduction#

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;
}
type MyReadonly<T> = any;
const todo: MyReadonly<Todo> = {
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;
}
type MyReadonly<T> = any;
const todo: MyReadonly<Todo> = {
title: 'Hey',
description: 'foobar',
};
todo.title = 'Hello'; // Error: cannot reassign a readonly property
todo.description = 'barFoo'; // Error: cannot reassign a readonly property
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type MyReadonly<T> = any;
 
/* _____________ Test Cases _____________ */
type cases = [Expect<Equal<MyReadonly<Todo1>, Readonly<Todo1>>>];
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
 
interface Todo1 {
title: string;
description: string;
completed: boolean;
meta: {
author: string;
};
}
Try
ts
/* _____________ Your Code Here _____________ */
type MyReadonly<T> = any;
 
/* _____________ Test Cases _____________ */
type cases = [Expect<Equal<MyReadonly<Todo1>, Readonly<Todo1>>>];
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
 
interface Todo1 {
title: string;
description: string;
completed: boolean;
meta: {
author: string;
};
}
Try
take the challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
Try
ts
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
Try
view more solutions