条件类型结果
预测输出 中等
题目
这段代码打印什么?
代码
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hello">;
type B = IsString<42>;
const a: A = "yes";
const b: B = "no";
console.log(a, b);
提示
条件类型对 string 选 "yes",对 number 选 "no"。
解释
IsString<"hello">:"hello" extends string 为 true,所以 A 为 "yes"。IsString<42>:42 extends string 为 false,所以 B 为 "no"。条件类型在编译时求值。
相关资源
相关课程
- 条件类型
学习条件类型。
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。