类型
# 元组
元组与数组相似,数组每一项可以是注解中的任意一个,元组则是数组每个位置必须与同位置注解类型相同。开发中不常用。
// 数组 某个位置的值可以是注解中的任何一个
const LOL: (string | number)[] = ["zed", 25, "darts"];
// 元组 每一项数据类型必须一致
const LOL: [string, string, number] = ["zed", "darts", 25];
1
2
3
4
5
2
3
4
5
# 联合类型
|
表示,满足其一即可
interface Waiter {
anjiao: boolean;
say: () => {};
}
interface Teacher {
anjiao: boolean;
skill: () => {};
}
// 联合类型
function judgeWho(animal: Waiter | Teacher) {}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 交叉类型
&
表示,会对类型进行合并。
type TOne = {x: number};
type TAll = TOne & {y: string};
// 相当于
interface TAll {
x: number
y: string
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
注意点
- 同名基础类型进行合并, 会变为never
interface A {
name: string
}
interface B {
name: number
}
type AB = A & B
// 相当于
interface AB {
name: never
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
- 同名非基础类型,可正常进行合并
interface A {
a: {x: string}
}
interface B {
a: {
y: string
}
}
type AB = A & B
// 相当于
interface AB {
a: {
x: string,
y: string
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 同名方法类型合并
- 目前还不知道,定义后该如何使用
interface A {
name: string
fun: (name: string) => void
}
interface B {
name: number
fun: (name: number, age: number) => void
}
type AB = A & B
const name: AB = {
name: 's',
fun: (name: number, age: number) => {}
}
// 错误提示
// Type '(name: number, age: number) => void' is not assignable to type '((name: string) => void) & ((name: number, age: number) => void)'.
// Type '(name: number, age: number) => void' is not assignable to type '(name: string) => void'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 泛型
- 箭头函数使用泛型
const foo = <T,>(x: T): T => x;
const foo = <T extends {}>(x: T): T => x;
const foo = <T extends Record<string, unknown>>(x: T): T => x;
const foo: <T>(x: T) => T = x => x;
const identity = <T,>(arg: T): T => {
console.log(arg);
return arg;
};
const renderAuthorize = <T>(Authorized: T): ((currentAuthority: CurrentAuthorityType) => T) => (
currentAuthority: CurrentAuthorityType,
): T => {
return
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 普通函数
// T 自定义名称
function myFun<T>(params: T[]) {
return params;
}
myFun <string> (["123", "456"]);
// 定义多个泛型
function join<T, P>(first: T, second: P) {
return `${first}${second}`;
}
join <number, string> (1, "2");
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- 泛型接口
interface Cart<T> {
list: T[];
}
let cart: Cart<{ name: string; price: number }> = {
list: [{ name: "hello", price: 10 }],
};
console.log(cart.list[0].name, cart.list[0].price);
1
2
3
4
5
6
7
2
3
4
5
6
7
编辑 (opens new window)
上次更新: 2022/06/19