-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8-readonly-2.ts
67 lines (59 loc) · 1.66 KB
/
8-readonly-2.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 8 - Readonly 2
*
* Implement a generic `MyReadonly2<T, K>` which takes two type argument `T` and `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>`.
*
* For example
*
* ```ts
* interface Todo {
* title: string
* description: string
* completed: boolean
* }
*
* const todo: MyReadonly2<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
* ```
*/
/* _____________ Your Code Here _____________ */
type MyReadonly2<T extends object, K extends keyof T = keyof T> = {
readonly [Key in K]: T[Key];
} & {
[Key in keyof T as Key extends K ? never : Key]: T[Key];
}
/* _____________ Test Cases _____________ */
import type { Alike, Expect } from '@type-challenges/utils'
type cases = [
Expect<Alike<MyReadonly2<Todo1>, Readonly<Todo1>>>,
Expect<Alike<MyReadonly2<Todo1, 'title' | 'description'>, Expected>>,
Expect<Alike<MyReadonly2<Todo2, 'title' | 'description'>, Expected>>,
Expect<Alike<MyReadonly2<Todo2, 'description' >, Expected>>,
]
// @ts-expect-error
type error = MyReadonly2<Todo1, 'title' | 'invalid'>
interface Todo1 {
title: string
description?: string
completed: boolean
}
interface Todo2 {
readonly title: string
description?: string
completed: boolean
}
interface Expected {
readonly title: string
readonly description?: string
completed: boolean
}