TypeScript 运算符
最后修改时间:2025年3月3日
TypeScript 中的运算符是用于对变量和值执行操作的符号。它们包括算术、比较、逻辑和高级运算符。本教程将通过实际示例探讨它们的用法。
算术运算符
算术运算符执行加法、减法、乘法和除法等数学运算。TypeScript 对数字运算强制执行类型安全。
arithmetic_operators.ts
let a: number = 10; let b: number = 5; console.log(a + b); // Output: 15 console.log(a - b); // Output: 5 console.log(a * b); // Output: 50 console.log(a / b); // Output: 2 console.log(a % b); // Output: 0
+
、-
、*
、/
和 %
运算符执行基本的算术运算。
比较运算符
比较运算符比较两个值并返回布尔结果。它们在条件语句中很有用。
comparison_operators.ts
let x: number = 10; let y: number = 20; console.log(x == y); // Output: false console.log(x != y); // Output: true console.log(x > y); // Output: false console.log(x < y); // Output: true console.log(x >= y); // Output: false console.log(x <= y); // Output: true
==
、!=
、>
、<
、>=
和 <=
运算符用于比较值。
逻辑运算符
逻辑运算符组合布尔值并返回布尔结果。它们用于条件逻辑。
logical_operators.ts
let isTrue: boolean = true; let isFalse: boolean = false; console.log(isTrue && isFalse); // Output: false console.log(isTrue || isFalse); // Output: true console.log(!isTrue); // Output: false
&&
、||
和 !
运算符分别执行逻辑“与”、“或”和“非”运算。
赋值运算符
赋值运算符将值赋给变量。它们还可以在赋值期间执行算术运算。
assignment_operators.ts
let num: number = 10; num += 5; // num = num + 5 console.log(num); // Output: 15 num -= 3; // num = num - 3 console.log(num); // Output: 12 num *= 2; // num = num * 2 console.log(num); // Output: 24 num /= 4; // num = num / 4 console.log(num); // Output: 6
+=
、-=
、*=
和 /=
运算符结合了算术和赋值。
三元运算符
三元运算符是条件语句的简写。它评估一个条件并返回两个值中的一个。
ternary_operator.ts
let age: number = 18; let status: string = age >= 18 ? "Adult" : "Minor"; console.log(status); // Output: Adult
三元运算符 ? :
简化了条件逻辑。
类型运算符
TypeScript 提供了 typeof
和 instanceof
等运算符,用于在运行时检查类型。
type_operators.ts
let value: any = "TypeScript"; console.log(typeof value); // Output: string class Animal {} let dog = new Animal(); console.log(dog instanceof Animal); // Output: true
typeof
运算符检查变量的类型,而 instanceof
检查对象是否是类的实例。
位运算符
位运算符对数字的二进制表示执行操作。它们在高层编程中很少使用。
bitwise_operators.ts
let a: number = 5; // Binary: 0101 let b: number = 3; // Binary: 0011 console.log(a & b); // Output: 1 (Binary: 0001) console.log(a | b); // Output: 7 (Binary: 0111) console.log(a ^ b); // Output: 6 (Binary: 0110) console.log(~a); // Output: -6 (Binary: 1010)
&
、|
、^
和 ~
运算符分别执行位“与”、“或”、“异或”和“非”运算。
空值合并运算符
如果左侧操作数为 null
或 undefined
,则空值合并运算符 ??
返回右侧操作数。
nullish_coalescing.ts
let input: string | null = null; let output: string = input ?? "Default Value"; console.log(output); // Output: Default Value
??
运算符可用于提供默认值。
可选链运算符
如果对象为 null
或 undefined
,则可选链运算符 ?.
在不引发错误的情况下访问对象的属性。
optional_chaining.ts
let user = { name: "John", address: { city: "New York" } }; console.log(user.address?.city); // Output: New York console.log(user.contact?.phone); // Output: undefined
?.
运算符可在访问嵌套属性时防止运行时错误。
最佳实践
- 使用严格相等:优先使用
===
而不是==
- 避免使用位运算符:仅在必要时使用它们
- 利用可选链:简化嵌套属性访问
- 使用空值合并:安全地提供默认值
- 类型安全:在操作前验证类型
来源
本教程通过实际示例介绍了 TypeScript 运算符。使用这些运算符可以编写高效且类型安全的 code。