Fork me on GitHub
秋染蒹葭

typescript技巧之一:参数类型约束

日常开发中我们经常会遇到标记联合类型了,一般都是出现在需要辨析联合类型的情况下,比如Redux中,一般就经常使用type来区分不同的action,进而通过判断语句进行类型守护

比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
interface Square {
kind: 'square';
size: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
// 有人仅仅是添加了 `Circle` 类型
// 我们可能希望 TypeScript 能在任何被需要的地方抛出错误
interface Circle {
kind: 'circle';
radius: number;
}
type Shape = Square | Rectangle | Circle;
function area(s: Shape) {
switch (s.kind) {
case 'square':
return s.size * s.size;
case 'rectangle':
return s.width * s.height;
case 'circle':
return Math.PI * s.radius ** 2;
default:
const _exhaustiveCheck: never = s;
}
}

参考资料

本文标题:typescript技巧之一:参数类型约束

文章作者:zhyjor

发布时间:2022年07月28日 - 15:07

最后更新:2023年10月11日 - 02:10

原始链接:https://zhyjor.github.io/2022/07/28/typescript技巧之一:参数类型约束/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

🐶 您的支持将鼓励我继续创作 🐶

热评文章