# Medium - Readonly key
# question
Implement a generic MyReadonlyKey<T, K>
which takes two type argument T
and K
.
实现一个通用的 MyReadonlyKey<T, K>
,它带有两种类型的参数 T
和 K
。
K
specify the set of properties of T that should set to Readonly. When K
is not provided, it should make all properties readonly just like the normal Readonly<T>
.
K
指定应设置为 Readonly
的 T
的属性集。如果未提供 K
,则应使所有属性都变为只读,就像普通的 Readonly<T>
一样。
For example
interface Todo {
title: string
description: string
completed: boolean
}
const todo: MyReadonlyKey<Todo, 'title' | 'description'> = {
title: "Hey",
description: "foobar",
completed: false,
}
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
todo.completed = true // OK
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# answer
- 实现一
type MyReadonlyKey<T, K extends keyof T = keyof T> = T & { readonly [P in K]: T[P] }
1
- 实现二
type Diff<A, B> = A extends B ? never : A
type MyReadonlyKey<T, K extends keyof T = keyof T> =
{ readonly [S in K]: T[S] }
& { [S in Diff<keyof T, K>]: T[S] }
1
2
3
4
5
2
3
4
5
# tips
和函数一样,参数可以提供默认值
keyof T
← 实现 Pick 实现 Readonly →