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';
- 作者:joye
- 出处:https://github.com/joye61