TypeScript 完全教程

第一章:TypeScript 基础

1.1 类型系统

TypeScript 中的基本类型和类型注解。

练习 1.1:基本类型示例

展示基本类型的使用。

基本类型示例
// 基本类型 let name: string = '张三'; let age: number = 25; let isStudent: boolean = true; let hobbies: string[] = ['阅读', '运动']; let scores: number[] = [90, 85, 95]; // 元组 let person: [string, number] = ['李四', 30]; // 枚举 enum Color { Red, Green, Blue } let color: Color = Color.Red; // 任意类型 let anyValue: any = '任意值'; anyValue = 42; // 空值 function logMessage(): void { console.log('消息已记录'); } // 空和未定义 let nullValue: null = null; let undefinedValue: undefined = undefined; // 类型断言 let someValue: any = '这是一个字符串'; let strLength: number = (someValue as string).length;

1.2 接口和类型别名

TypeScript 中的接口和类型别名。

练习 1.2:接口和类型别名示例

展示接口和类型别名的使用。

接口和类型别名示例
// 接口定义 interface Person { name: string; age: number; sayHello(): void; } // 接口实现 class Student implements Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } sayHello(): void { console.log(`你好,我是${this.name}`); } } // 可选属性 interface Config { name: string; age?: number; } // 只读属性 interface Point { readonly x: number; readonly y: number; } // 类型别名 type StringOrNumber = string | number; type Callback = (data: string) => void; // 联合类型 function processValue(value: string | number): void { if (typeof value === 'string') { console.log(value.toUpperCase()); } else { console.log(value.toFixed(2)); } } // 交叉类型 interface A { a: string; } interface B { b: number; } type C = A & B;

第二章:类和泛型

2.1 类

TypeScript 中的类。

练习 2.1:类示例

展示类的使用。

类示例
// 类定义 class Animal { protected name: string; constructor(name: string) { this.name = name; } move(distance: number = 0): void { console.log(`${this.name}移动了${distance}米`); } } // 继承 class Dog extends Animal { private breed: string; constructor(name: string, breed: string) { super(name); this.breed = breed; } bark(): void { console.log('汪汪!'); } move(distance: number = 5): void { console.log('奔跑中...'); super.move(distance); } } // 抽象类 abstract class Shape { abstract getArea(): number; printArea(): void { console.log(`面积: ${this.getArea()}`); } } class Circle extends Shape { constructor(private radius: number) { super(); } getArea(): number { return Math.PI * this.radius * this.radius; } } // 访问修饰符 class Person { public name: string; private age: number; protected gender: string; constructor(name: string, age: number, gender: string) { this.name = name; this.age = age; this.gender = gender; } }

2.2 泛型

TypeScript 中的泛型。

练习 2.2:泛型示例

展示泛型的使用。

泛型示例
// 泛型函数 function identity(arg: T): T { return arg; } // 泛型接口 interface GenericIdentityFn { (arg: T): T; } // 泛型类 class GenericNumber { zeroValue: T; add: (x: T, y: T) => T; } // 泛型约束 interface Lengthwise { length: number; } function loggingIdentity(arg: T): T { console.log(arg.length); return arg; } // 在泛型约束中使用类型参数 function getProperty(obj: T, key: K) { return obj[key]; } // 泛型默认类型 interface DefaultGeneric { value: T; } // 泛型工具类型 type Partial = { [P in keyof T]?: T[P]; }; type Readonly = { readonly [P in keyof T]: T[P]; }; type Pick = { [P in K]: T[P]; };

第三章:装饰器和高级类型

3.1 装饰器

TypeScript 中的装饰器。

练习 3.1:装饰器示例

展示装饰器的使用。

装饰器示例
// 类装饰器 function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype); } @sealed class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } // 方法装饰器 function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`调用方法: ${propertyKey}`); console.log(`参数: ${JSON.stringify(args)}`); const result = originalMethod.apply(this, args); console.log(`结果: ${result}`); return result; }; return descriptor; } class Calculator { @log add(a: number, b: number): number { return a + b; } } // 属性装饰器 function format(formatString: string) { return function (target: any, propertyKey: string) { let value = target[propertyKey]; const getter = function() { return value; }; const setter = function(newVal: string) { value = newVal.padStart(10, '0'); }; Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true }); }; } class User { @format('0000000000') id: string; }

3.2 高级类型

TypeScript 中的高级类型。

练习 3.2:高级类型示例

展示高级类型的使用。

高级类型示例
// 条件类型 type TypeName = T extends string ? 'string' : T extends number ? 'number' : T extends boolean ? 'boolean' : T extends undefined ? 'undefined' : T extends Function ? 'function' : 'object'; // 映射类型 type Readonly = { readonly [P in keyof T]: T[P]; }; type Partial = { [P in keyof T]?: T[P]; }; // 索引类型 function getProperty(obj: T, key: K) { return obj[key]; } // 类型推断 type ReturnType = T extends (...args: any[]) => infer R ? R : any; // 类型保护 function isString(value: any): value is string { return typeof value === 'string'; } function processValue(value: string | number) { if (isString(value)) { return value.toUpperCase(); } else { return value.toFixed(2); } } // 类型兼容性 interface Named { name: string; } class Person { name: string; } let p: Named; p = new Person();

第四章:模块和命名空间

4.1 模块

TypeScript 中的模块。

练习 4.1:模块示例

展示模块的使用。

模块示例
// 导出模块 // person.ts export interface Person { name: string; age: number; } export class Student implements Person { constructor(public name: string, public age: number) {} } // 默认导出 export default class Teacher { constructor(public name: string) {} } // 导入模块 // main.ts import { Person, Student } from './person'; import Teacher from './person'; // 重命名导入 import { Person as PersonType } from './person'; // 导入所有 import * as PersonModule from './person'; // 动态导入 async function loadModule() { const module = await import('./person'); const person = new module.Student('张三', 20); }

4.2 命名空间

TypeScript 中的命名空间。

练习 4.2:命名空间示例

展示命名空间的使用。

命名空间示例
// 命名空间定义 namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } const lettersRegexp = /^[A-Za-z]+$/; const numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } export class ZipCodeValidator implements StringValidator { isAcceptable(s: string) { return s.length === 5 && numberRegexp.test(s); } } } // 使用命名空间 let validators: { [s: string]: Validation.StringValidator } = {}; validators['ZIP code'] = new Validation.ZipCodeValidator(); validators['Letters only'] = new Validation.LettersOnlyValidator(); // 命名空间分割 // Validation.ts namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } } // LettersOnlyValidator.ts /// namespace Validation { const lettersRegexp = /^[A-Za-z]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } } // 别名 import Q = Validation.ZipCodeValidator; let validator = new Q();

第五章:配置和工具

5.1 TypeScript 配置

TypeScript 的配置文件。

练习 5.1:TypeScript 配置示例

展示 TypeScript 配置的使用。

TypeScript 配置示例
// tsconfig.json { "compilerOptions": { "target": "es6", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src", "sourceMap": true, "declaration": true, "experimentalDecorators": true, "emitDecoratorMetadata": true }, "include": [ "src/**/*" ], "exclude": [ "node_modules", "dist" ] } // 编译命令 // package.json { "scripts": { "build": "tsc", "watch": "tsc -w", "start": "node dist/index.js" } }

5.2 工具和最佳实践

TypeScript 开发工具和最佳实践。

练习 5.2:工具和最佳实践示例

展示工具和最佳实践的使用。

工具和最佳实践示例
// ESLint 配置 // .eslintrc.js module.exports = { parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended' ], rules: { '@typescript-eslint/explicit-function-return-type': 'error', '@typescript-eslint/no-explicit-any': 'error' } }; // Prettier 配置 // .prettierrc { "semi": true, "trailingComma": "es5", "singleQuote": true, "printWidth": 100, "tabWidth": 4 } // 类型定义文件 // types.d.ts declare module '*.svg' { const content: string; export default content; } // 最佳实践 // 1. 使用严格模式 // 2. 避免使用 any // 3. 使用接口而不是类型别名 // 4. 使用 readonly 修饰符 // 5. 使用类型保护 // 6. 使用泛型 // 7. 使用枚举 // 8. 使用命名空间 // 9. 使用装饰器 // 10. 使用模块

学习建议

建议按照章节顺序学习,每完成一个练习后再进行下一个。可以通过创建实际项目来实践所学知识。