跳到主要内容

ReadOnly

介绍

不要使用内置的Readonly<T>,自己实现一个。

泛型 Readonly<T> 会接收一个 泛型参数,并返回一个完全一样的类型,只是所有属性都会是只读 (readonly) 的。

也就是不可以再对该对象的属性赋值。

例如:

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

起点

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;
};
}
 
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;
};
}
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
 
//扩展 实现数组的readonly
type readOnlyArr<T extends any[]> = {
readonly [K in keyof T]: T[K]
};
type ReadOnlyArr2<T extends any[]> = readonly [...T];
type ReadOnlyArr3<T> = T extends any[] ? readonly [...T] : T;
 
function toReadOnlyArr<T extends any[]>(arr: T): readonly [...T] {
return arr
};
 
type DeepReadOnlyArr<T> = T extends any[]
? readonly [...{[K in keyof T]: DeepReadOnlyArr<T[K]>}]
: T;
 
 
ts
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
 
//扩展 实现数组的readonly
type readOnlyArr<T extends any[]> = {
readonly [K in keyof T]: T[K]
};
type ReadOnlyArr2<T extends any[]> = readonly [...T];
type ReadOnlyArr3<T> = T extends any[] ? readonly [...T] : T;
 
function toReadOnlyArr<T extends any[]>(arr: T): readonly [...T] {
return arr
};
 
type DeepReadOnlyArr<T> = T extends any[]
? readonly [...{[K in keyof T]: DeepReadOnlyArr<T[K]>}]
: T;
 
 
view more solutions