三、接口

# 三、接口
# 对象类型接口
interface List {
// 只读属性:不可更改
readonly id: number;
name: string;
// 字符串索引签名
[x: string]: any;
// 可选属性
age?: number
}
interface Result {
data: List[]
}
function render(result: Result) {
result.data.forEach((value) => {
console.log(value.id, value.name)
if (value.age) {
console.log(value.age)
}
})
}
let result = {
data: [
{id: 1, name: 'A', sex: 'male'},
{id: 2, name: 'B'}
]
}
// 字面量形式,编译类型检查会报错
// 绕过类型检查的方式:
// 1. 通过给一个变量
// 2. 使用类型断言
// 3. 使用字符串索引签名
//
// 类型断言有两种写法:建议用写法一,写法二在react里面有冲突
// 写法一:
render({
data: [
{id: 1, name: 'A', sex: 'male'},
{id: 2, name: 'B'}
]
} as Result)
// 写法二:
render(<Result>{
data: [
{id: 1, name: 'A', sex: 'male'},
{id: 2, name: 'B'}
]
})
render(result)
// 数字索引字符串数组
interface StringArray {
[index: number]: string
}
let charts: StringArray = ['A', 'B']
// 字符串索引字符串数组
interface Names {
[x: string]: any;
// y:number;
[z: number]: string
}
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
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
# 函数类型接口
# 函数定义
// 函数定义
function sub(x: number, y: number) {
return x - y
}
let sub2: (x: number, y: number) => number
type sub3 = (x: number, y: number) => number
interface sub4 {
(x: number, y: number): number
}
// 可选参数
function sub5(x: number, y?: number) {
return y ? x - y : x;
}
sub5(1)
// 在必选参数前的默认参数是不可省略的,必选传入明确的undefined,来获取默认值
// 在必选参数后的默认参数是可以不传的
function sub6(x: number, y = 0, z: number, q = 1) {
return x + y + z + q
}
console.log(sub6(1, undefined, 3))
// 当参数不确定的时候,可以使用剩余参数
function sub7(x: number, ...rest: number[]) {
// 数组的reduce方法求和
return x + rest.reduce((pre, cur) => pre + cur)
}
console.log(sub7(1, 2, 3, 4, 5))
// 函数重返
function sub8(...rest: number[]): number;
function sub8(...rest: string[]): string;
function sub8(...rest: any[]): any {
let first = rest[0];
if (typeof first === 'string') {
return rest.join('')
}
if (typeof first === 'number') {
return rest.reduce((pre, cur) => pre + cur)
}
}
console.log(sub8(1, 2, 3))
console.log(sub8('a', 'b', 'c'))
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
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
上次更新: 2021/04/22, 00:08:06