typescript之advancedTypes

在componentWillReceiveProps里面setState之后是不会接着触发componentWillReceiveProps的,否则那就是死循环了。

1.union types

正如字面意思上面所说,union type就是联合类型。万万没想到在typescript中,字符串字面量也能够成为类型,如下所示:

1
2
3
type St = "string";
const faith: St = "string";
const freedom: St = "string2"; // 报错,St类型的变量的值只能够是string

在某些场合下,我们希望某个字符串只能是某几个可选的值之一,那么这个时候使用union type将会特别方便,如下所示:

1
2
3
4
type St = "Man" | "Women" | "She" | "He" | "Me";
const theMan: St = "Man";
const theWomen: St = "Women";
const errorIsValid: St = "Aha"; // error

下面再看一个使用union type的例子,感受下他对类型系统所作出的作用:

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
interface I1 {
type: "1";
value: string
}

interface I2 {
type: "2";
value: string
}

interface I3 {
type: "3";
value: string
}

interface I4 {
type: "4";
value: string
}

type smlz2 = I1 | I2 | I3 | I4;

function init(param: smlz2) {
switch(param.type) {
case "1":
param.value = "one";
break;
case "2":
param.value = "two";
break;
case "3":
param.value = "three";
break;
default:
const neverChoice: never = param;
}
}


const par: smlz2 = { type: "4", value: "four" };
init(par); // 报错,要解决这个问题的话,那么就需要在case 3这个分支后面加上对case 4的处理。

2.泛型方法

不多说,直接介绍使用方法,下面是一个泛型方法的使用方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const getData = <T>(url: string): Promise<T> => {
return fetch(url).then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
}

interface ApiRes {
errorMes: string;
content: object;
status: number;
};

getData<ApiRes>("/api/mockMe").then(res => {
console.log(res.content);
});

3.泛型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class List<T> {
private data: T[] = [];

public getList(): T[] {
return this.data;
}

public add(item: T) {
this.data.push(item);
}
}

interface Person {
name: string;
age: number;
}

let peopleList = new List<Person>();
peopleList.add({ name: 'hahahai', age: 23 });
peopleList.add({ name: 'hahahai', nickName: 'xh' }); // 报错

4.如果想在react中使用redux的话,那么只需要安装redux即可,无需安装type声明文件,因为redux package里面已经包含了type声明文件。