视频位置 TypeScript快速梳理_中篇 视频位置 00:39:49
type 可以为任意类型创建别名,让代码更简洁、可读性更强,同时能更⽅便地进⾏类型复⽤和扩展。
1. 基本⽤法
类型别名使⽤ type 关键字定义, type 后跟类型名称,例如下⾯代码中 num 是类型别名。
E.g
//使用 拼音shuzi 代表 number类型 或者说 给 number类型 起了一个新名字叫 shuzi
type shuzi = number
let a: shuzi
a = 1002. 联合类型 //或
联合类型是⼀种⾼级类型,它表示⼀个值可以是⼏种不同类型之⼀。
//定义的 Status类型,可以是 number ,也可以是 string
type Status = number | string
//写一个字面量类型Gender, 可以是 男 ,也可以是 女
type Gender = '男' | '⼥'
function printStatus(data: Status):void {
console.log(status);
}
function logGender(str:Gender){
console.log(str)
}
//测试:
printStatus(404);
printStatus('200');
printStatus('501');
logGender('男')
logGender('⼥')3.交叉类型 //并
交叉类型(Intersection Types)允许将多个类型合并为⼀个类型。合并后的类型将拥有所有被合并类型的成员。交叉类型通常⽤于对象类型。
//⾯积
//定义 Area 是一个对象(该对象有属性 height width)
type Area = {
height: number; //⾼
width: number; //宽
};
//地址
type Address = {
num: number; //楼号
cell: number; //单元号
room: string; //房间号
};
// 定义类型House,且House是Area和Address组成的 交叉类型
type House = Area & Address;
const house: House = {
height: 180,
width: 75,
num: 6,
cell: 3,
room: '702'
};
