OSDN Git Service

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