回答編集履歴
1
Base型をベースにConvert型を定義する
test
CHANGED
@@ -2,7 +2,7 @@
|
|
2
2
|
|
3
3
|
|
4
4
|
|
5
|
-
```
|
5
|
+
```typescript
|
6
6
|
|
7
7
|
let convert: Convert = {
|
8
8
|
|
@@ -13,3 +13,69 @@
|
|
13
13
|
} as Convert;
|
14
14
|
|
15
15
|
```
|
16
|
+
|
17
|
+
|
18
|
+
|
19
|
+
## (追記)Base型をベースにConvert型を定義する
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
[TypeScriptでDiff型を表現する - Qiita](https://qiita.com/cotttpan/items/999fe07d079298c35e0c)を参考に不要なプロパティを除いて継承してみました。共通部分のクラスを定義して継承した方がわかりやすそうな気がしますが。
|
24
|
+
|
25
|
+
|
26
|
+
|
27
|
+
```typescript
|
28
|
+
|
29
|
+
type DiffKey<T extends string, U extends string> = (
|
30
|
+
|
31
|
+
& {[P in T]: P }
|
32
|
+
|
33
|
+
& {[P in U]: never }
|
34
|
+
|
35
|
+
& { [x: string]: never }
|
36
|
+
|
37
|
+
)[T];
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
type Omit<T, K extends keyof T> = Pick<T, DiffKey<keyof T, K>>;
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
interface Base {
|
46
|
+
|
47
|
+
a: number;
|
48
|
+
|
49
|
+
b: string;
|
50
|
+
|
51
|
+
dontUse: string;
|
52
|
+
|
53
|
+
dontUse2: string;
|
54
|
+
|
55
|
+
}
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
interface Convert extends Omit<Base, 'dontUse' | 'dontUse2'> {
|
60
|
+
|
61
|
+
c: string;
|
62
|
+
|
63
|
+
}
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
let convert: Convert = {
|
68
|
+
|
69
|
+
a: 1,
|
70
|
+
|
71
|
+
b: '2',
|
72
|
+
|
73
|
+
c: 'sample',
|
74
|
+
|
75
|
+
};
|
76
|
+
|
77
|
+
console.log(convert); // { a: 1, b: '2', c: 'sample' }
|
78
|
+
|
79
|
+
convert.dontUse = 'dontUse'; // compile error: 'dontUse' does not exist in type 'Convert'
|
80
|
+
|
81
|
+
```
|