标题中几个概念都是TS类型应用中非常好用的,类型应用好处很多,在此不细谈,主要讲讲元组等具体使用。基本概念不涉及,有一定阅读门槛。
元组
let x: [string, number];
x = ['1', 2];
// 限定顺序
// x = [1, '2'] error
元组转联合 Tuple[number]技巧
type Tuple = [string, number, boolean];
type Union = Tuple[number]; // string | number | boolean
泛型转Utility Types Tuple2Union类比Partial
type Tuple2Union<T extends readonly unknown[]> = T[number];
type Tuple2 = [string, number, boolean];
type Union2 = Tuple2Union<Tuple2>; // string | number | boolean
元组转mapType
type Tuple3 = ['blue', 'yellow', 'red'];
type MappedTuple = {
[k in Tuple3[number]]: string;
};
type MappedTuple = {
blue: string;
yellow: string;
red: string;
}
extends ele extands arr
type Includes1<T extends readonly any[], P> = P extends T[number] ? true : false;
type Includes2<T extends readonly any[], P> = T[number] extends P ? true : false;
type isPillarMen = Includes1<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Wamuu'>; // true
type isPillarMen2 = Includes2<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Wamuu'>; // false
枚举
可以用数字枚举和字符串枚举 但是不要用混合枚举
enum Color {
Red,
Greeen,
Blue
}
// 编译为js相当于
let jsColor = { '0': 'Red', '1': 'Greeen', '2': 'Blue', Red: 0, Greeen: 1, Blue: 2 };
let c1: Color = Color.Blue; // 可以当对象用
enum CardinalDirection {
North = 'N',
East = 'E',
South = 'S',
West = 'W'
}
// 编译后为
let jsCD = { North: 'N', East: 'E', South: 'S', West: 'W' };
数字枚举和字符串枚举的区别就在这里
loose type-checking 弱类型校验
const color1: Color = 4; // 超过枚举范围,不会报错
const color2: Color.Red = 5; // 虽然类型声明比较奇怪,但是不会报错
// const color3: Color ='6' // Error
// let cd1: CardinalDirection = 'N' // Error
所以用枚举尽量使用字符串枚举,或者是赋值使用如下写法
const c2: Color = Color.Red;
if (c2 === Color.Red) {
}
枚举转mapType
type ColorMap = {
[key in Color]: string;
};
type ColorMap = {
0: string;
1: string;
2: string;
}
常数枚举
const enum Direction {
Up,
Down,
Left,
Right
}
// 编译后为
const jsDir = { Up: 0, Down: 1, Left: 2, Right: 3 }; // 没有数字当key的了
let directions = [Direction.Up, Direction.Down, Direction.Left, Direction.Right]; // [0, 1, 2, 3]
声明枚举
declare enum Direction2 {
Up,
Down,
Left,
Right
}
不能作为值来使用,暂时不知道怎么用
枚举转联合
const DirectionObj = {
North: 'N',
East: 'E',
South: 'S',
West: 'W'
};
type union1 = keyof typeof Direction;
// type union1 = "Up" | "Down" | "Left" | "Right"
type union2 = keyof typeof DirectionObj;
// type union2 = "North" | "East" | "South" | "West"
type转联合
type point = { x: number; y: number };
type union3 = keyof point;
满足条件的函数foo
// foo('xx', {name: 'hello'}) // correct
// foo(3232, 232) // correct
// foo('xx', 123) // error!
其定义为:
function foo(...args: [string, {name: string}] | [number, number]) {}