登录/注册
小开开
2649
占位
2
占位
0
浏览量
占位
粉丝
占位
关注
TypeScript-类型别名
小开开
2020-12-03 17:17:39 2020-12-03
64
0

类型别名

别名不会创建一个新的类型,它只是原类型的一个引用,和原类型完全等价,它的语法形式如下:

type 别名 = 类型 ;

类型别名可以简化程序,提高可读性和可维护性。以下都是合法的类型别名声明:

// 数字类型别名
type myNumber = number;
// 布尔类型别名
type myBoolean = boolean;
// 联合类型别名
type transition = 'EASE' | 'EASEIN' | 'EASEOUT';
// 联合类型别名
type StringOrNumber = string | number;
// 联合类型别名
type Text = string | { text: string };
// 泛型的实际类型别名
type NameLookup = Dictionary<string, Person>;
// 通过类型查询定义别名
type ObjectStatics = typeof Object;
// 泛型函数别名
type Callback<T> = (data: T) => void;
// 元组泛型别名
type Pair<T> = [T, T];
// 泛型的实际类型别名
type Coordinates = Pair<number>;
// 联合类型别名
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };

声明了别名以后,别名就相当于是一个类型的标识符,可以用于注解语法中:

// 声明transition为联合类型的别名
type transition = 'EASE' | 'EASEIN' | 'EASEOUT';
// transition此时是一个类型标识符
const boxTransition: transition = 'EASE';
暂无评论