TypeScript 基础
最后修改于 2025 年 3 月 20 日
TypeScript 通过静态类型定义扩展了 JavaScript,实现了编译时错误检查和更好的工具支持。本教程通过实际示例介绍了变量、函数、接口和类。
变量和类型
TypeScript 变量使用 let
或 const
声明。显式类型注解确保值与指定的`数据类型`匹配。
variables.ts
let age: number = 30; const username: string = "Alice"; let isActive: boolean = true; console.log(`${username} is ${age} years old.`);
TypeScript 支持 number
、string
、boolean
、Array
和复杂类型。类型检查可防止不匹配的赋值。
函数
函数指定参数类型和返回类型。此示例演示了一个类型安全的函数。
functions.ts
function calculateArea(width: number, height: number): number { return width * height; } const area = calculateArea(5, 4); console.log(`Area: ${area}`); // Output: Area: 20
箭头函数的工作方式类似。TypeScript 会强制参数类型并检查返回值。
接口
接口定义对象的形状。它们能够对对象的属性和方法进行类型检查。
interfaces.ts
interface User { id: number; name: string; email?: string; // Optional property } const user1: User = { id: 1, name: "Bob" }; console.log(user1.name); // Output: Bob
接口支持可选属性(用 ?
标记),并且可以被其他接口继承。
类
TypeScript 类支持访问修饰符和类型检查的属性。
classes.ts
class Vehicle { constructor(public make: string, private model: string) {} getDescription(): string { return `${this.make} ${this.model}`; } } const car = new Vehicle("Toyota", "Corolla"); console.log(car.getDescription()); // Output: Toyota Corolla
public
和 private
修饰符控制属性的访问。类可以实现接口以获得额外的类型安全。
类型推断
当变量被初始化时,TypeScript 会自动推断类型。此示例展示了隐式类型。
inference.ts
let score = 95; // Type inferred as number let items = ["Book", "Pen"]; // Type inferred as string[] // score = "Ninety-five"; // Error: Type 'string' not assignable to 'number'
当 TypeScript 可以从初始值可靠地推断类型时,显式类型注解是可选的。
最佳实践
- 启用严格模式: 在 tsconfig.json 中使用
"strict": true
进行严格的类型检查 - 避免使用
any
: 尽量少用any
类型以保持类型安全 - 使用接口: 为对象和函数参数定义契约
- 利用类型推断: 当初始化值清晰时,省略显式类型
来源
本教程通过实际示例介绍了 TypeScript 的核心功能。掌握这些概念,即可构建健壮、易于维护的应用程序。