OSDN Git Service

Regular updates
[twpd/master.git] / typescript.md
1 ---
2 title: TypeScript
3 category: JavaScript libraries
4 layout: 2017/sheet
5 ---
6
7 ### About
8
9 TypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.
10
11 ### Basic types
12
13 ```ts
14 any
15 void
16
17 boolean
18 number
19 string
20
21 null
22 undefined
23
24 bigint
25 symbol
26
27 string[]          /* or Array<string> */
28 [string, number]  /* tuple */
29
30 string | null | undefined   /* union */
31
32 never  /* unreachable */
33 unknown
34 ```
35
36 ```ts
37 enum Color {
38   Red,
39   Green,
40   Blue = 4
41 };
42
43 let c: Color = Color.Green
44 ```
45
46 ### Declarations
47
48 ```ts
49 let isDone: boolean
50 let isDone: boolean = false
51 ```
52
53 ```ts
54 function add (a: number, b: number): number {
55   return a + b
56 }
57
58 // Return type is optional
59 function add (a: number, b: number) { ... }
60 ```
61
62 ## Type assertions
63
64 #### Variables
65 ```ts
66 let len: number = (input as string).length
67 let len: number = (<string> input).length  /* not allowed in JSX */
68 ```
69
70 #### Functions
71 ```ts
72 function object(this: {a: number, b: number}, a: number, b: number) {
73   this.a = a;
74   this.b = b;
75   return this;
76 }
77
78 // this is used only for type declaration
79 let a = object(1,2);
80 // a has type {a: number, b: number}
81 ```
82
83
84 ## Interfaces
85
86 ### Inline
87
88 ```ts
89 function printLabel (options: { label: string }) {
90   console.log(options.label)
91 }
92
93 // Note the semicolon
94 function getUser (): { name: string; age?: number } {
95 }
96 ```
97
98 ### Explicit
99
100 ```ts
101 interface LabelOptions {
102   label: string
103 }
104
105 function printLabel(options: LabelOptions) { ... }
106 ```
107
108 ### Optional properties
109
110 ```ts
111 interface User {
112   name: string;
113   age?: number;
114 }
115 ```
116
117 ### Read only
118
119 ```ts
120 interface User {
121   readonly name: string
122 }
123 ```
124
125 ### Dynamic keys
126
127 ```ts
128 {
129   [key: string]: Object[]
130 }
131 ```
132
133 ## Type aliases
134
135 ### Type aliases
136
137 ```ts
138 type Name = string | string[]
139 ```
140
141 ### Intersection
142
143 ```ts
144 interface Colorful { ... }
145
146 interface Circle { ... }
147  
148 type ColorfulCircle = Colorful & Circle;
149 ```
150
151 ## Function types
152
153 ```ts
154 interface User { ... }
155
156 function getUser(callback: (user: User) => any) { callback({...}) }
157
158 getUser(function (user: User) { ... })
159 ```
160
161 ## Classes
162
163 ```ts
164 class Point {
165   x: number
166   y: number
167   static instances = 0
168   constructor(x: number, y: number) {
169     this.x = x
170     this.y = y
171   }
172 }
173 ```
174
175 #### Inheritance
176
177 ```ts
178 class Point {...}
179
180 class Point3D extends Point {...}
181
182 interface Colored {...}
183
184 class Pixel extends Point implements Colored {...}
185 ```
186
187 #### Short fields initialisation
188
189 ```ts
190 class Point {
191   static instances = 0;
192   constructor(
193     public x: number,
194     public y: number,
195   ){}
196 }
197 ```
198
199 #### Fields which do not require initialisation
200 ```ts
201 class Point {
202   public someUselessValue!: number;
203   ...
204 }
205 ```
206
207 ## Generics
208
209 ```ts
210 class Greeter<T> {
211   greeting: T
212   constructor(message: T) {
213     this.greeting = message
214   }
215 }
216
217 let greeter = new Greeter<string>('Hello, world')
218 ```
219
220 ## Modules
221
222 ```ts
223 export interface User { ... }
224 ```
225
226 ## Type extraction
227
228 ```ts
229 interface Building {
230   room: {
231     door: string;
232     walls: string[];
233   };
234 }
235
236 type Walls = Building['room']['walls']; // string[]
237 ```
238
239 ## Keyof Type Operator
240
241 ```ts
242 type Point = { x: number; y: number };
243
244 type P = keyof Point; // x | y
245 ```
246
247 ## Conditional Types
248
249 ```ts
250 // SomeType extends OtherType ? TrueType : FalseType;
251
252 type ToArray<T> = T extends any ? T[] : never;
253
254 type StrArrOrNumArr = ToArray<string | number>; // string[] | number[]
255 ```
256
257 ### Inferring
258
259 ```ts
260 type GetReturnType<T> = T extends (...args: unknown[]) => infer R
261   ? R
262   : never;
263
264 type Num = GetReturnType<() => number>; // number
265 ```
266
267 ```ts
268 type First<T extends Array<any>> = T extends [infer F, ...infer Rest] ? F : never;
269
270 type Str = First<['hello', 1, false]>; // 'hello'
271 ```
272
273 ## Literal Type
274
275 ```ts
276 const point = { x: 4, y: 2 }; // { x: number, y: number }
277
278 const literalPoint = { x: 4, y: 2 } as const; // { readonly x: 4, readonly y: 2 };
279 ```
280
281 ## Template Literal Types
282
283 ```ts
284 type SpaceChar = ' ' | '\n' | '\t';
285
286 type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;
287
288 type Str = TrimLeft<'    hello'>; // 'hello'
289 ```