判别联合收窄
预测输出 中等
题目
这段代码打印什么?
代码
type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
function area(sh: Shape) {
if (sh.kind === "circle") return Math.PI * sh.r ** 2;
return sh.s ** 2;
}
console.log(area({ kind: "square", s: 3 }));
提示
判别符收窄为 square,面积 = 3*3 = 9。
解释
形状 kind 为 "square",跳过 if 分支。TypeScript 在 else 分支将 sh 收窄为 { kind: "square"; s: number }。面积 = s^2 = 3^2 = 9。
相关资源
相关课程
- 联合与交叉
学习联合与交叉类型。
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。