0%

Typescript学习

TypeScript概要

  • 编译期行为
  • 不改变运行时行为
  • 不会引入额外的开销
  • 契约高于实现

示例

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
type A = {
a: string;
b: number;
};

type B = {
c: string;
d: number;
};

type C = A | B;

type D = A & B;

const testD: C = { a: "test", b: 2 };

type Tuple = [number, string];

const array: Tuple = [1, "2"];

type Site = "samll" | "default" | "big"; // Set

type MapB = {
small: string;
default: number;
big: string;
}; // Map

// type map2Set = keyof MapB; // => small | default | big
type map2Set = MapB[keyof MapB]; // => string | number | string

type set2Map = {
[key in Site]: string;
};
// => type set2Map = {
// small: string,
// default: string,
// big: string
// }

// map取索引值
type MapTest = {
test: number;
};

type valueOfIndex = MapTest["test"]; // => number

type Person = {
readonly name: string;
age?: number;
};

const person: Person = {
name: "John"
};

// person.name = "test"; // => get the error

//同态变换
type PartialTest = Partial<Person>; //

//set生成同类型的map(只能生成同类型)
type SizeSet = "small" | "default" | "big";

type SizeMap = Record<SizeSet, number>;
// type SizeMap = {
// small: number,
// default: number,
// big: number
// }

//类型递归
type DeepReadOnly<T> = {
readonly [P in keyof T]: DeepReadOnly<T[P]>;
};
//readonly [P in keyof T]: [DeepReadOnly<T[P]>]
type TestObject = {
a: {
b: {
c: number;
};
};
};

type DeepTypeMap = DeepReadOnly<TestObject>;

const obj: DeepTypeMap = { a: { b: { c: 2 } } };
// obj.a.b.c = 2; will get type error

interface SomeProps {
a: string;
b: number;
c: (e: MouseEvent) => void;
d: (e: TouchEvent) => void;
}
// 如何得到 'c' | 'd' ?

type GetFixedParams<T, C> = {
[P in keyof T]: T[P] extends C ? P : never;
}[keyof T];

type TestObj = GetFixedParams<SomeProps, Function> // "c" | "d"

参考来源 https://juejin.im/post/5d4285ddf265da03dd3d514b?utm_source=gold_browser_extension#heading-15