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 propertytodo.description = 'barFoo'; // Error: cannot reassign a readonly property
View on GitHubts
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 propertytodo.description = 'barFoo'; // Error: cannot reassign a readonly property
起点
ts
/* _____________ Your Code Here _____________ */typeMyReadonly <T > = any;/* _____________ Test Cases _____________ */typeType 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.cases = [Expect <Equal <MyReadonly <Todo1 >,Readonly <Todo1 >>>];interfaceTodo1 {title : string;description : string;completed : boolean;meta : {author : string;};}
take the challengets
/* _____________ Your Code Here _____________ */typeMyReadonly <T > = any;/* _____________ Test Cases _____________ */typeType 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.cases = [Expect <Equal <MyReadonly <Todo1 >,Readonly <Todo1 >>>];interfaceTodo1 {title : string;description : string;completed : boolean;meta : {author : string;};}
解决方案
Spoiler warning // Click to reveal answer
ts
typeMyReadonly <T > = {readonly [K in keyofT ]:T [K ];};//扩展 实现数组的readonlytypereadOnlyArr <T extends any[]> = {readonly [K in keyofT ]:T [K ]};typeReadOnlyArr2 <T extends any[]> = readonly [...T ];typeReadOnlyArr3 <T > =T extends any[] ? readonly [...T ] :T ;functiontoReadOnlyArr <T extends any[]>(arr :T ): readonly [...T ] {returnarr };typeDeepReadOnlyArr <T > =T extends any[]? readonly [...{[K in keyofT ]:DeepReadOnlyArr <T [K ]>}]:T ;
ts
typeMyReadonly <T > = {readonly [K in keyofT ]:T [K ];};//扩展 实现数组的readonlytypereadOnlyArr <T extends any[]> = {readonly [K in keyofT ]:T [K ]};typeReadOnlyArr2 <T extends any[]> = readonly [...T ];typeReadOnlyArr3 <T > =T extends any[] ? readonly [...T ] :T ;functiontoReadOnlyArr <T extends any[]>(arr :T ): readonly [...T ] {returnarr };typeDeepReadOnlyArr <T > =T extends any[]? readonly [...{[K in keyofT ]:DeepReadOnlyArr <T [K ]>}]:T ;