-
Notifications
You must be signed in to change notification settings - Fork 0
/
00008-medium-readonly-2.ts
73 lines (57 loc) · 1.76 KB
/
00008-medium-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
68
69
70
71
72
73
/*
8 - Readonly 2
-------
by Anthony Fu (@antfu) #medium #readonly #object-keys
### Question
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
```
> View on GitHub: https://tsch.js.org/8
*/
/* _____________ Your Code Here _____________ */
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [k in K]: T[k];
} & Omit<T, K>;
/* _____________ 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>>
];
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;
}
/* _____________ Further Steps _____________ */
/*
> Share your solutions: https://tsch.js.org/8/answer
> View solutions: https://tsch.js.org/8/solutions
> More Challenges: https://tsch.js.org
*/