TypeScript Challenge - 实现一个通用MyReadonly2<T, K>,它带有两种类型的参数T和K
题目
实现一个通用MyReadonly2<T, K>
,它带有两种类型的参数T
和K
。
K
指定应设置为Readonly的属性集(如果T
)。如果未提供K
,则应使所有属性都变为只读,就像普通的Readonly<T>
一样。
例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| interface Todo { title: string description: string completed: boolean }
const todo: MyReadonly2<Todo, 'title' | 'description'> = { title: "Hey", description: "foobar", completed: false, }
todo.title = "Hello" todo.description = "barFoo" todo.completed = true
|
测试用例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import { Alike, Expect } from '@type-challenges/utils'
type cases = [ Expect<Alike<MyReadonly2<Todo1>, Readonly<Todo1>>>, Expect<Alike<MyReadonly2<Todo1, 'title' | 'description'>, Expected>>, ]
interface Todo1 { title: string description?: string completed: boolean }
interface Expected { readonly title: string readonly description?: string completed: boolean }
|
答案
1 2 3 4 5
| type MyReadonly2<T, K extends keyof T = keyof T> = { readonly [P in K]: T[P] } & { [P in keyof T]: T[P] }
|
蒙圈了