2.高级类型

发布时间 2023-12-12 20:20:27作者: 前端自信逐梦者

联合类型 | 类型别名 | 交叉类型

7.1 联合类型,使用 | 来连接多个类型

let person: 'male' | 'female';
person = 'male';
person = 'female';

let strOrBool: string | boolean;
strOrBool = 'hello';
strOrBool = false;

7.2 类型别名(自定义类型),使用关键字type

// 自定义的类型名称最好大写开头且语义化
type MyType = (string | number)[];
let arr1:MyType = [1,'2'];
let arr2:MyType = [1,2,'3','4'];

7.3 交叉类型,使用 & 来连接多个类型

// 这里CustomType的类型是never
type CustomType = string & number;
// 函数入参中使用联合类型
interface People {
  name: string;
  age: number;
}
interface Man {
  sex: string;
}
let func = (man: People & Man): void => {};
func({
  name: '张三',
  age: 18,
  sex: '男',
});