標題中幾個概念都是TS類型應(yīng)用中非常好用的作谚,類型應(yīng)用好處很多三娩,在此不細談,主要講講元組等具體使用妹懒∪讣啵基本概念不涉及,有一定閱讀門檻彬伦。
元組
let x: [string, number];
x = ['1', 2];
// 限定順序
// x = [1, '2'] error
元組轉(zhuǎn)聯(lián)合 Tuple[number]技巧
type Tuple = [string, number, boolean];
type Union = Tuple[number]; // string | number | boolean
泛型轉(zhuǎn)Utility Types Tuple2Union類比Partial
type Tuple2Union<T extends readonly unknown[]> = T[number];
type Tuple2 = [string, number, boolean];
type Union2 = Tuple2Union<Tuple2>; // string | number | boolean
元組轉(zhuǎn)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
枚舉
可以用數(shù)字枚舉和字符串枚舉 但是不要用混合枚舉
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' };
數(shù)字枚舉和字符串枚舉的區(qū)別就在這里
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) {
}
枚舉轉(zhuǎn)mapType
type ColorMap = {
[key in Color]: string;
};
type ColorMap = {
0: string;
1: string;
2: string;
}
常數(shù)枚舉
const enum Direction {
Up,
Down,
Left,
Right
}
// 編譯后為
const jsDir = { Up: 0, Down: 1, Left: 2, Right: 3 }; // 沒有數(shù)字當key的了
let directions = [Direction.Up, Direction.Down, Direction.Left, Direction.Right]; // [0, 1, 2, 3]
聲明枚舉
declare enum Direction2 {
Up,
Down,
Left,
Right
}
不能作為值來使用回官,暫時不知道怎么用
枚舉轉(zhuǎn)聯(lián)合
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轉(zhuǎn)聯(lián)合
type point = { x: number; y: number };
type union3 = keyof point;
滿足條件的函數(shù)foo
// foo('xx', {name: 'hello'}) // correct
// foo(3232, 232) // correct
// foo('xx', 123) // error!
其定義為:
function foo(...args: [string, {name: string}] | [number, number]) {}
本文內(nèi)容均參閱https://zhuanlan.zhihu.com/p/432942317