字数
829 字
阅读时间
4 分钟
使用类型注释
ts
/ ** 用户信息 */
interface User {
name: string;
age: number;
}
const p: User = {}
第三方声明文件
ts
// typing.d.ts
declare module 'antd-dayjs-webpack-plugin'使用命名空间
在代码量较大的情况下,为了避免各种变量名冲突, 可以将相同模块的函数、类、接口等都放置在命名空间内
ts
// src/typings/domain.d.ts
declare namespace Domains {
interface ListItem {
id: string;
domainId: string;
domainName: string;
}
interface ListReq {
rows: ListItem[];
}
interface CreateItem {
locationId: string;
}
interface EditItem extends CreateItem {
id: string;
}
}
// 使用
const columns: Domains.ListItem[] = []收窄变量类型
- 类型断言
值 as 类型<类型>值
- 类型守卫
instanceof- 用于判断number,string,boolean或symbol四种类型typeof- 用于判断一个实例是否属于某个类in- 用于判断一个属性 / 方法是否属于某个对象
- 双重断言
声明一个常量 Map
字典值使用 enum 枚举声明
ts
const enum ActivityEnum {
Edit,
Preonline,
Online,
Offline
}
const statusMap: Readonly<Record<Activities, string>> = {
[ActivityEnum.Edit]: '编辑中',
[ActivityEnum.Preonline]: '待上线',
[ActivityEnum.Online]: '在线',
[ActivityEnum.Offline]: '离线',
}区别 enum 和 const enum

使用 enum 声明会得到一个嵌套的对象,即 ActivityStatus2[0] 和 ActivityStatus2["Edit"] 都能互相访问到对象,是一个实际存在的 object;使用 const enum 得到的产物中并不会存在这样的一个对象,只会转变为原来的 magic number
enum会被编译成普通 Javascript 对象,在运行时引用const enum会在编译时直接内联替换 value,不产生运行时消耗
当项目中大量了使用枚举之后,使用普通 enum 会生成大量的对象增大主 bundle 的体积,从性能的角度和产物整洁的角度来看,const enum 会是首选
什么情况使用枚举
- 对于 value 是
number类型- 如果需要 index 互访问,使用常规枚举
enum - 否则,使用常量枚举
const enum,优化性能
- 如果需要 index 互访问,使用常规枚举
- 对于 value 是
string类型,使用对象字面量type Status = "PREPARE" | "RUNNING" | "DONE"
as const
ts
const SHAPES = {
SQUARE: 'square',
CIRCLE: 'circle',
} as const;
type Shape = typeof SHAPES;
type Shapes = keyof Shape; // 'SQUARE' | 'CIRCLE'
type ValueOf<T> = T[keyof T];
const SHAPES = {
SQUARE: 'square',
CIRCLE: 'circle',
} as const;
type Shape = typeof SHAPES;
type Values = ValueOf<Shape>; // 'square' | 'circle'约束 string 字面量
ts
type JumpPathType = 'center' | 'about' | 'home';
function gotoPage(path: JumpPathType){
// do something
}网络请求时候使用泛型
ts
get<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
return this.request({ ...config, method: 'GET' }, options);
}
post<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
return this.request({ ...config, method: 'POST' }, options);
}
enum Api {
AREA_RECORD = '/cascader/getAreaRecord',
}
export const areaRecord = (data: AreaParams) =>
defHttp.post<AreaModel[]>({ url: Api.AREA_RECORD, data });使用 typeof 快速获取对象类型
ts
const info = {
type: VersionStatus.Invalid,
title: '快来更新手机淘宝',
subTitle: '你的版本太低,暂不支持互动~立刻升级参与活动吧!',
okText: '马上更新',
};
type InfoType = typeof info;快速添加和删除属性
ts
interface Student {
name: string;
age: number;
}
type Student2 = Pick<Student, 'name'>
type Student3 = Omit<Student, 'name'>
type Student4 = Student & { gender: 0 | 1 }
interface Student5 extends Student {
gender: 0 | 1
}使用 unknown 代替 any
ts
function fn(arg: unknown) {
if (arg instanceof Error) {
console.log('err', arg)
} else if (typeof arg === 'function') {
console.log('fnc', arg)
}
}