-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09.ts
541 lines (473 loc) · 11.5 KB
/
09.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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// 高级类型
// 交叉类型
{
function extend<T, U>(first: T, second: U): T & U {
let result = <T & U>{};
for (let id in first) {
(<T>result)[id] = first[id];
// (<any>result)[id] = (<any>first)[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
(<U>result)[id] = second[id];
// (<any>result)[id] = (<any>second)[id];
}
}
return result;
}
class Person {
constructor(public name: string) { }
}
interface Loggable {
log(something: string): void;
}
class ConsoleLogger implements Loggable {
log(something: string) {
console.log(something)
}
}
var jim = extend(new Person('Jim'), new ConsoleLogger());
var n = jim.name;
jim.log(n);
}
// 联合类型
// 联合类型表示一个值可以是几种类型之一
{
function padLeft(value: string, padding: string | number) {
if (typeof padding === 'number') {
return Array(padding + 1).join(' ') + value;
}
if (typeof padding === 'string') {
return padding + value;
}
throw new Error(`Expected string or number, got ${padding}.`);
}
padLeft('Hello world', 4);
}
{
interface Bird {
layEggs();
fly();
}
interface Fish {
layEggs();
swim();
}
function getSmallPet(): Fish | Bird {
return {
layEggs() { },
fly() { },
swim() { },
}
}
let pet = getSmallPet();
pet.layEggs();
// pet.swim(); // Error
// 类型保护和类型区分
{
if ((<Fish>pet).swim) {
(<Fish>pet).swim();
} else {
(<Bird>pet).fly();
}
/**
* !用户自定义的类型保护
* @类型谓词 pet is Fish
*
* @param {(Fish | Bird)} pet
* @returns {pet is Fish}
*/
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
// typeof 类型保护
// 这样做其实是没必要的
function isNumber(x: any): x is number {
return typeof x === 'number';
}
function isString(x: any): x is string {
return typeof x === 'string';
}
function padLeft1(value: string, padding: string | number) {
if (isNumber(padding)) {
return Array(padding + 1).join(" ") + value;
}
if (isString(padding)) {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
// instanceof 类型保护
interface Padder {
getPadderingString(): string;
}
class SpaceRepeatingPadder implements Padder {
constructor(private numSpaces: number) { }
getPadderingString() {
return Array(this.numSpaces + 1).join(' ');
}
}
class StringPadder implements Padder {
constructor(private value: string) { }
getPadderingString() {
return this.value;
}
}
function getRandomPadder() {
return Math.random() < 0.5
? new SpaceRepeatingPadder(4)
: new StringPadder(' ');
}
let padder: Padder = getRandomPadder();
if (padder instanceof SpaceRepeatingPadder) {
padder; // 类型细化为'SpaceRepeatingPadder'
}
if (padder instanceof StringPadder) {
padder; // 类型细化为'StringPadder'
}
}
}
// 可为 null 的类型
// 类型检查器认为 null与 undefined可以赋值给任何类型
// --strictNullChecks 标记可以解决此问题
{
let s = "foo";
// s = null; // 错误, 'null'不能赋值给'string'
let sn: string | null = "bar";
sn = null; // 可以
// sn = undefined; // error, 'undefined'不能赋值给'string | null'
/**
* ! 可选参数和可选属性
* 使用了 --strictNullChecks,可选参数会被自动地加上 | undefined
* 即 f(x: number, y?: number) 相当于 f(x: number, y?: number | undefined)
* 此时 null 不能赋值给 y
*
* @param {number} x
* @param {number} [y]
* @returns
*/
function f(x: number, y?: number) {
return x + (y || 0);
}
f(1, 2);
f(1);
f(1, undefined);
// f(1, null); // error
// 可选属性也会有同样的处理
class C {
a: number;
b?: number;
}
let c = new C();
c.a = 12;
// c.a = undefined; // error
// c.a = null; // error
c.b = 13;
c.b = undefined;
// c.b = null; // error
// 类型保护和类型断言
// function broken(name: string | null): string {
// function postfix(epithet: string) {
// return name.charAt(0) + '. the ' + epithet; // Error
// }
// name = name || 'Bob';
// return postfix('great');
// }
function fixed(name: string | null): string {
function postfix(epithet: string) {
return name!.charAt(0) + '. the ' + epithet;
}
name = name || "Bob";
return postfix("great");
}
}
// 类型别名
{
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
} else {
return n();
}
}
// 类型别名也可以是泛型
type Container<T> = { value: T }
// 可以使用类型别名来在属性里引用自己
type Tree<T> = {
value: T;
left: Tree<T>;
right: Tree<T>;
}
interface Tree1<T> {
value: T;
left: Tree1<T>;
right: Tree1<T>;
}
type Tree2<T> = Tree1<T>;
// 与交叉类型一起使用
type LinkedList<T> = T & { next: LinkedList<T> };
interface Person {
name: string;
}
var people: LinkedList<Person> = {} as LinkedList<Person>;
var s = people.name;
var s = people.next.name;
var s = people.next.next.name;
var s = people.next.next.next.name;
}
// 接口 vs. 类型别名
type Alias = { num: number }
interface Interface {
num: number;
}
declare function aliased(arg: Alias): Alias;
declare function interfaced(arg: Interface): Interface;
// 类型别名不能被 extends和 implements
// 类型别名不能扩展
interface InterfaceA extends Interface {
name: string;
}
interface InterfaceA {
test: number;
}
// 字符串字面量类型
{
type Easing = 'ease-in' | 'ease-out' | 'ease-in-out';
class UIElement {
animate(dx: number, dy: number, easing: Easing) {
switch (easing) {
case 'ease-in':
break;
case 'ease-out':
break;
case 'ease-in-out':
break;
default:
break;
}
}
}
let button = new UIElement();
button.animate(0, 0, 'ease-in');
// button.animate(0, 0, "uneasy"); // error
}
{
enum Easing {
easeIn = 'ease-in',
easeOut = 'ease-out',
easeInOut = 'ease-in-out'
}
class UIElement {
animate(dx: number, dy: number, easing: Easing) {
switch (easing) {
case Easing.easeIn:
break;
case Easing.easeOut:
break;
case Easing.easeInOut:
break;
default:
break;
}
}
}
let button = new UIElement();
button.animate(0, 0, Easing.easeIn);
// button.animate(0, 0, 'ease-in'); // error
}
{
// 字符串字面量类型还可以用于区分函数重载
function createElement(tagName: 'img'): HTMLImageElement;
function createElement(tagName: 'input'): HTMLInputElement;
function createElement(tagName: string): HTMLElement {
return new HTMLElement;
}
}
// 数字字面量类型
{
function rollDie(): 1 | 2 | 3 | 4 | 5 | 6 {
return 1;
}
}
// 可辨识联合
{
interface Square {
kind: 'square';
size: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
interface Circle {
kind: 'circle';
radius: number;
}
type Shape = Square | Rectangle | Circle | Triangle;
function area(s: Shape) {
switch (s.kind) {
case 'square':
return s.size * s.size;
case 'rectangle':
return s.width * s.height;
case 'circle':
return Math.PI * s.radius ** 2;
default:
break;
}
}
// 完整性检查
interface Triangle {
kind: 'triangle';
height: number;
bottom: number;
}
type Shape1 = Square | Rectangle | Circle | Triangle;
// 方法-:启用 --strictNullChecks 并且指定一个返回值类型
// function area1(s: Shape1): number { // 函数缺少结束 return 语句,返回类型不包括 "undefined"
// switch (s.kind) {
// case 'square':
// return s.size * s.size;
// case 'rectangle':
// return s.width * s.height;
// case 'circle':
// return Math.PI * s.radius ** 2;
// }
// }
// 方法二:使用 never类型
function assertNever(x: never): never {
throw new Error('Unexpected object: ' + x);
}
function area2(s: Shape1) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
// default: return assertNever(s); // 类型“Triangle”的参数不能赋给类型“never”的参数
}
}
}
// 多态的 this 类型
{
class BasicCalculator {
public constructor(protected value: number = 0) { }
public currentValue(): number {
return this.value;
}
public add(operand: number): this {
this.value += operand;
return this;
}
public multiply(operand: number): this {
this.value *= operand;
return this;
}
}
let v = new BasicCalculator(2)
.multiply(5)
.add(1)
.currentValue();
class ScientificCalculator extends BasicCalculator {
public constructor(value = 0) {
super(value);
}
public sin() {
this.value = Math.sin(this.value);
return this;
}
}
let v1 = new ScientificCalculator(2)
.multiply(5)
.sin()
.add(1)
.currentValue();
}
// 索引类型
{
function pluck1(o, names) {
return names.map(n => o[n]);
}
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
return names.map(n => o[n]);
}
interface Person {
name: string;
age: number;
}
let person: Person = {
name: 'Jarid',
age: 35
};
let strings: string[] = pluck(person, ['name']);
function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
return o[name];
}
let name: string = getProperty(person, 'name');
let age: number = getProperty(person, 'age');
// let unknown = getProperty(person, 'unknown'); // error, 'unknown' is not in 'name' | 'age'
// 索引类型和字符串索引签名
interface Map<T> {
[key: string]: T;
}
let keys: keyof Map<number>; // string
let value: Map<string>['foo']; // number
}
// 映射类型
{
interface Person {
name: string;
age: number;
}
interface PersonPartial {
name?: string;
age?: number;
}
interface PersonReadonly {
readonly name: string;
readonly age: number;
}
type Partial<T> = {
[P in keyof T]?: T[P];
}
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
type PersonPartial1 = Partial<Person>;
type PersonReadonly1 = Readonly<Person>;
type Keys = 'option1' | 'option2';
type Flags = { [K in Keys]: boolean };
type Flags1 = {
option1: boolean;
option2: boolean;
}
type Nullable<T> = { [P in keyof T]: T[P] | null };
type Partial1<T> = { [P in keyof T]?: T[P] };
type Proxy<T> = {
get(): T;
set(value: T): void;
}
type Proxify<T> = {
[P in keyof T]: Proxy<T[P]>;
}
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
// 由映射类型进行推断
function unproxify<T>(t: Proxify<T>): T {
let result = {} as T;
for (const k in t) {
result[k] = t[k].get();
}
return result;
}
let originalProps = unproxify(proxyProps);
}