学习typescrip-01

252 阅读4分钟

变量

var

 1//代码
2for (var i = 0; i < 10; i++) {
3    setTimeout(function(console.log(i); }, 100 * i);
4}
5
6//结果
710
810
910
1010
1110
1210
1310
1410
1510
1610
17
18// 解决代码,使用立即执行的函数表达式(IIFE)来捕获每次迭代时i的值:
19for (var i = 0; i < 10; i++) {
20    // capture the current state of 'i'
21    // by invoking a function with its current value
22    (function(i{
23        setTimeout(function(console.log(i); }, 100 * i);
24    })(i);
25}
26
27
28// 结果
290
301
312
323
334
345
356
367
378
389
39
40// 使用let
41for (let i = 0; i < 10 ; i++) {
42    setTimeout(function({console.log(i); }, 100 * i);
43}
44
45// 结果
460
471
482
493
504
515
526
537
548
559

解构

数组解构

 1let input = [12];
2let [first, second] = input;
3console.log(first); // outputs 1
4console.log(second); // outputs 2
5
6// 函数参数
7function f([first, second]: [number, number]{
8    console.log(first);
9    console.log(second);
10}
11f(input);

数组里使用…语法创建剩余变量

1let [first, ...rest] = [1234];
2console.log(first); // outputs 1
3console.log(rest); // outputs [ 2, 3, 4 ]

对象解构

1let o = {
2    a"foo",
3    b12,
4    c"bar"
5};
6let { a, b } = o;

接口

定义

接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

 1interface LabelledValue {
2  label: string;
3}
4
5function printLabel(labelledObj: LabelledValue{
6  console.log(labelledObj.label);
7}
8
9let myObj = {size10label"Size 10 Object"};
10printLabel(myObj);

可选属性

 1interface SquareConfig {
2  color?: string;
3  width?: number;
4}
5
6function createSquare(config: SquareConfig): {color: string; area: number} {
7  let newSquare = {color"white"area100};
8  if (config.color) {
9    newSquare.color = config.color;
10  }
11  if (config.width) {
12    newSquare.area = config.width * config.width;
13  }
14  return newSquare;
15}
16
17let mySquare = createSquare({color"black"});

只读属性

1interface Point {
2    readonly x: number;
3    readonly y: number;
4}
5
6let p1: Point = { x10y20 };
7p1.x = 5// error!    

typescript具有ReadonlyArray的类型

1let a: number[] = [1234];
2let ro: ReadonlyArray<number> = a;
3ro[0] = 12// error!
4ro.push(5); // error!
5ro.length = 100// error!
6a = ro; // error!

但是可以类型推断重写

1a = ro as number[];

// 除了color和width的属性,还有其他的附件属性,如下

1interface SquareConfig {
2    color?: string;
3    width?: number;
4    [propName: string]: any;
5}

函数类型

 1interface SearchFunc {
2  (source: string, subString: string): boolean;
3}
4
5let mySearch: SearchFunc;
6mySearch = function(source: string, subString: string{
7  let result = source.search(subString);
8  return result > -1;
9}
10
11let mySearch: SearchFunc;
12mySearch = function(src: string, sub: string): boolean {
13  let result = src.search(sub);
14  return result > -1;
15}
16
17let mySearch: SearchFunc;
18mySearch = function(src, sub{
19    let result = src.search(sub);
20    return result > -1;
21}

declare

使用第三方不是 TypeScript 编写的模块时,我们需要下载对应的声明文件,如果没有声明文件,则自己写

接口(interface)和类型别名(type alias)

interface只能定义对象类型,type声明的方式可以定义组合类型,交叉类型和原始类型