https://mp.weixin.qq.com/s/4tM37jZDHftkWKvGncVgIw
1,原理是只有nerver才能赋值给never
如果你漏处理了一个类型,导致它没有被认领,就会报类型错误;
ts
declare enum Color {
Red,
Yellow,
Blue,
Pink,
}
declare let color: Color;
switch (color) {
case Color.Red:
// do something
break;
case Color.Yellow:
// do something
break;
case Color.Blue:
// do something
break;
default:
// 不能将类型“Color”分配给类型“never”。
let exhaustiveCheck: never = color;
break;
}
- 使用”互斥“替代”联合“类型;
适用于”转换按钮“这样的场景
ts
type XORUser = XOR<Visitor, Registered>;
”要么同时有,要么同时没有“
ts
interface Registered {
email: string;
registerTime: number;
level: number;
}
type XORStruct = XOR<{}, Registered>;
const val1: XORStruct = {}; // √
// X
const val2: XORStruct = {
email: '[email protected]',
};
// √
const val3: XORStruct = {
email: '[email protected]',
registerTime: Date.now(),
level: 9999,
};
- (string & {}) 交叉,就不会出现PresetSize被合并进string的情况了
ts
type PresetSize = 'mini' | 'middle' | 'large';
type Size = PresetSize | (string & {});
let size1: Size = 'mini';
let size2: Size = '200px';