一、TypeScript简介
TypeScript是由Microsoft开发的开源编程语言,作为JavaScript的超集,它添加了静态类型系统和对ES6+特性的支持,旨在提升代码可维护性和开发效率。它的优势在于通过类型注解实现编译时类型检查,减少运行时错误,同时保留JavaScript的灵活性。
二、环境搭建与配置
-
安装依赖:
-
需先安装Node.js和npm(Node.js包管理器),用于运行TypeScript编译器。
-
通过npm全局安装TypeScript编译器:
npm install -g typescript安装后验证版本:
tsc --version。
-
-
项目初始化:
-
创建
tsconfig.json配置文件:tsc --init -
关键配置示例(支持模块化与现代语法):
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "strict": true, "outDir": "./dist" }, "include": ["src/**/*.ts"] }此配置启用严格类型检查,并指定输出目录。
-
-
开发工具:
- 推荐使用Visual Studio Code(VSCode),安装TypeScript插件以增强代码提示和调试功能。
三、核心语法与类型系统
-
基础数据类型:
-
boolean、number、string等基本类型:let isDone: boolean = false; let count: number = 10; let name: string = "TypeScript"; -
特殊类型:
any(动态类型)、void(无返回值)、null/undefined。
-
-
复合类型:
-
数组:
let list: number[] = [1, 2, 3]或Array<number>。 -
元组(Tuple) :固定类型顺序的数组,如
let x: [string, number] = ["hello", 10]。 -
枚举(Enum) :定义命名常量集:
enum Role { Admin, Editor, Viewer } let user: Role = Role.Admin; ```:ml-citation{ref="3,4" data="citationList"}。
-
-
函数与接口:
-
函数类型注解:
function add(x: number, y: number): number { return x + y; } -
接口(Interface)定义对象结构:
interface User { id: number; name: string; roles?: string[]; // 可选属性 } const user: User = { id: 1, name: "Alice" }; ```:ml-citation{ref="3,4" data="citationList"}。
-
-
类与面向对象:
-
支持类、继承、访问修饰符(
public、private):class Animal { constructor(public name: string) {} move(distance: number = 0) { console.log(`${this.name} moved ${distance}m.`); } } class Dog extends Animal { bark() { console.log("Woof!"); } } ```:ml-citation{ref="4,6" data="citationList"}。
-
四、高级特性
-
泛型(Generics) :
-
创建可复用组件,支持多种类型:
typescriptCopy Code function identity<T>(arg: T): T { return arg; } let output = identity<string>("hello"); ```:ml-citation{ref="4,6" data="citationList"}。
-
-
模块(Modules) :
-
使用
export和import组织代码:// utils.ts export function log(message: string) { console.log(message); } // app.ts import { log } from './utils'; log("Module loaded"); ```:ml-citation{ref="3,5" data="citationList"}。
-
-
类型守卫与高级类型:
- 类型守卫(如
typeof、instanceof)缩小变量类型范围。 - 映射类型(Mapped Types)和条件类型(Conditional Types)用于复杂类型转换。
- 类型守卫(如
五、编译与调试实践
-
编译运行:
- 单文件编译:
tsc filename.ts生成同名JS文件。 - 监控模式:
tsc -p tsconfig.json --watch自动编译变更。
- 单文件编译:
-
调试技巧:
-
使用
ts-node直接运行TS文件:npm install -g ts-node ts-node src/app.ts ```:ml-citation{ref="3" data="citationList"}。 -
类型断言处理不确定值:
let el = document.getElementById("root") as HTMLDivElement。
-