TypeScript 表达式
最后修改时间:2025年3月3日
TypeScript 中的表达式是值、变量、运算符和函数组成的组合,它们计算为单个值。TypeScript 通过添加类型注解和类型安全性来增强 JavaScript 表达式。本教程通过实际示例探讨各种表达式。
基本算术表达式
TypeScript 支持带类型安全性的算术表达式。此示例演示了基本的算术运算。
arithmetic.ts
const sum: number = 10 + 5; const difference: number = 10 - 5; const product: number = 10 * 5; const quotient: number = 10 / 5; console.log(sum); // Output: 15 console.log(difference); // Output: 5 console.log(product); // Output: 50 console.log(quotient); // Output: 2
TypeScript 确保算术运算在数字上执行,从而防止与类型相关的错误。
字符串连接
字符串连接使用 + 运算符组合字符串。TypeScript 强制执行字符串类型。
string_concat.ts
const firstName: string = "John"; const lastName: string = "Doe"; const fullName: string = firstName + " " + lastName; console.log(fullName); // Output: John Doe
逻辑表达式
逻辑表达式计算为布尔值。TypeScript 确保逻辑运算的类型安全性。
logical.ts
const isAdult: boolean = true; const hasLicense: boolean = false; const canDrive: boolean = isAdult && hasLicense; console.log(canDrive); // Output: false
三元运算符
三元运算符提供了一种简洁的方式来编写条件表达式。
ternary.ts
const age: number = 20; const status: string = age >= 18 ? "Adult" : "Minor"; console.log(status); // Output: Adult
模板字面量
模板字面量允许使用反引号在字符串中嵌入表达式。
template_literals.ts
const name: string = "Alice";
const greeting: string = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
数组表达式
可以使用表达式初始化和操作数组。TypeScript 确保数组元素的类型安全性。
array.ts
const numbers: number[] = [1, 2, 3, 4, 5]; const doubled: number[] = numbers.map(num => num * 2); console.log(doubled); // Output: [2, 4, 6, 8, 10]
对象表达式
可以使用表达式创建和操作对象。TypeScript 强制执行属性类型。
object.ts
const person: { name: string, age: number } = {
name: "Bob",
age: 30
};
console.log(person.name); // Output: Bob
函数表达式
函数可以用作表达式。TypeScript 确保参数和返回值的类型安全性。
function_expression.ts
const add: (a: number, b: number) => number = function(a, b) {
return a + b;
};
console.log(add(5, 10)); // Output: 15
类型断言
类型断言允许覆盖 TypeScript 的推断类型。请谨慎使用它们。
type_assertion.ts
const input: unknown = "123"; const numberValue: number = (input as string).length; console.log(numberValue); // Output: 3
最佳实践
- 类型安全性:始终使用类型注解以获得清晰性
- 可读性:编写易于理解的表达式
- 避免类型断言:仅在必要时使用它们
- 一致性:遵循一致的编码模式
- 测试:通过单元测试验证表达式
来源
本教程通过实际示例涵盖了 TypeScript 表达式。实现这些模式可以编写更安全、更易于维护的代码。