一、基础类型
1.布尔值
const hasData: boolean = false;
2.字符串
const name: string = 'ysj';
3.数字
const age: number = 22;
4.数组
const arr1: Array<number> = [1, 2, 3, 4];
interface ArrList {
name!: string;
age?: number;
}
const arr2: ArrList[] = [{name: 'ysj', age: 23}, {name: 'lh'}];
// (1)在元素类型后面加上[]
// (2)使用数组泛型Array<元素类型>
5.枚举
enum ObjType {
name: string;
age: number;
isMarry?: boolean;
}
const person1 = {name: 'ysj', age: 22, isMarry: false};
const person2 = {name: 'lh', age: 23};
6.any
当不确定变量是什么类型的时候使用
7.void
当一个函数没有返回值时使用
handelClick(): void {
console.log('点击了');
}
8.Null和Undifined(作用不大)
const u: undefined = undefined;
const n: null = null;
9.Never
表示永不存在值的类型,例如抛出异常的时候
error(msg: string): never {
throw new Error(message);
}
二、Typescript新特性
1.可选链式操作符(Optional Chaining) v3.7可用
// 数据:
const userInfo = {
name: 'ysj',
age: 22,
authList: ['user-manager', 'user-delete'] // 用户权限
};
// 需求:如果该用户没有权限时,显示无数据
// html
<div v-if="hasAuth">
<span v-for="item in userInfo.authList" :key="item">{{item}}</span>
<div>
<div v-else>无权限干任何事儿呀</div>
// js
// 普通写法
get hasAuth(): boolean {
return this.userInfo && this.userInfo.authList && this.userInfo.authList.length;
};
// 可选链式
get hasAuth(): boolean {
return this.userInfo?.authList?.length
};
2.双问号操作符(Nullish Coalescing) v3.7可用
const a = false;
const res = a || 'foo'; // res = 'foo' 错误
// 当a等于0或flase时,也会给res赋值为foo,这时候好像不太符合要求。这时可以使用双问号操作符,只有a为null或undefined时才会被赋予默认值
const a = false;
const res = a ?? 'foo'; // res = false; 正确