TypeScript - 条件判断
TypeScript - 条件语句
Section titled “TypeScript - 条件语句”条件语句(Conditional statements)允许程序根据特定条件评估结果是 true 还是 false 来执行不同的代码块。这些结构是控制程序执行流程的基础。
基本结构涉及评估一个条件(一个布尔表达式)。如果条件为 true,则执行一个代码块。可选地,如果条件为 false,则可以执行另一个代码块。
TypeScript 使用与来自 JavaScript 或其他 C 风格语言的开发者所熟悉的条件语句。它们通过评估布尔表达式来工作:
condition ? statement_if_true : statement_if_false; // 三元运算符 (Ternary Operator)
if (condition) { // 如果条件为 true,则执行此代码块} else if (another_condition) { // 如果另一个条件为 true,则执行此代码块} else { // 如果所有先前的条件都为 false,则执行此代码块}
switch (expression) { case value1: // 如果 expression === value1,则执行此代码 break; // 重要:防止穿透 (fall-through) case value2: // 如果 expression === value2,则执行此代码 break; default: // 如果没有匹配的 case,则执行此代码}TypeScript 将这些决策制定结构分类如下:
| 语句 (Statement) | 描述 (Description) |
|---|---|
| if 语句 | 仅在指定的布尔条件为 true 时执行一个代码块。 |
| if…else 语句 | 如果条件为 true,执行一个代码块;如果条件为 false,执行另一个代码块。 |
| else if 语句 | 允许按顺序检查多个条件。通常与最终的 else 块一起使用,用于默认情况。 |
| 嵌套 if 语句 (Nested if) | 将一个 if 或 else if 语句放置在另一个 if 或 else if 块内,以实现更复杂的逻辑。 |
| switch 语句 | 评估一个表达式,并执行与匹配的 case 标签对应的代码。使用严格比较 (===)。 |
| 三元运算符 (?:) | if...else 语句的简写形式,适用于条件赋值或简单表达式。 |
类型收窄 (Type Narrowing)
Section titled “类型收窄 (Type Narrowing)”TypeScript 中与条件语句相关的一个关键特性是类型收窄(Type Narrowing)。当你在 if 块内执行诸如 typeof variable === 'string' 或 variable instanceof MyClass 等检查时,TypeScript 会理解在该块内,变量的类型已被收窄。这允许你安全地访问该特定类型独有的属性或方法,而不会出现编译器错误。
function processInput(input: string | number) { if (typeof input === 'number') { // 在此块内,TypeScript 知道 'input' 是一个 number 类型 console.log(`Processing number: ${input.toFixed(2)}`); } else { // 在此块内,TypeScript 知道 'input' 是一个 string 类型 console.log(`Processing string: ${input.toUpperCase()}`); }}
processInput(123.456);processInput("hello world");理解类型收窄对于在 TypeScript 中编写类型安全的条件逻辑至关重要,尤其是在处理联合类型 (union types) 时。
最佳实践 (Best Practices)
Section titled “最佳实践 (Best Practices)”- 使用严格相等 (
===和!==) 而非宽松相等 (==和!=),以避免意外的类型强制转换 (type coercion)。 - 除非明确意图并文档化了穿透行为 (fall-through),否则在
switch的case中始终包含break语句。 - 在
switch语句中使用defaultcase 来处理意外值。 - 保持条件清晰易读。复杂的条件最好分解成更小的部分或辅助函数 (helper functions)。
- 利用
typeof、instanceof、属性检查 ('prop' in obj) 和自定义类型守卫 (custom type guards) 来进行类型收窄,以便在使用联合类型时编写更安全的代码。