TypeScript 从入门到精通:完整教程与实战应用(二)
8. 模块和命名空间
模块:
// math.ts
export function add(x: number, y: number): number {return x + y;
}// app.ts
import { add } from './math';
console.log(add(1, 2));
命名空间:
namespace Validation {export interface StringValidator {isAcceptable(s: string): boolean;}const lettersRegexp = /^[A-Za-z]+$/;export class LettersOnlyValidator implements StringValidator {isAcceptable(s: string) {return lettersRegexp.test(s);}}
}let validators: { [s: string]: Validation.StringValidator } = {};
validators["Letters only"] = new Validation.LettersOnlyValidator();
9. 装饰器 (Decorators)
装饰器是一种特殊类型的声明:
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;}
}
第三部分:TypeScript 实战 (70-100%)
10. 与前端框架集成
React + TypeScript:
import React, { useState } from 'react';interface Props {name: string;age?: number;
}const Greeting: React.FC<Props> = ({ name, age = 18 }) => {const [count, setCount] = useState<number>(0);return (<div><h1>Hello {name}, age {age}</h1><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>Click me</button></div>);
};export default Greeting;
Vue + TypeScript:
<template><div><h1>Hello {{ name }}, age {{ age }}</h1><p>You clicked {{ count }} times</p><button @click="increment">Click me</button></div>
</template><script lang="ts">
import { defineComponent, ref } from 'vue';export default defineComponent({props: {name: {type: String,required: true},age: {type: Number,default: 18}},setup(props) {const count = ref(0);function increment() {count.value++;}return {count,increment};}
});
</script>
11. Node.js 后端开发
Express + TypeScript:
import express, { Request, Response } from 'express';interface User {id: number;name: string;
}const app = express();
app.use(express.json());const users: User[] = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' }
];app.get('/users', (req: Request, res: Response<User[]>) => {res.json(users);
});app.post('/users', (req: Request<{}, {}, User>, res: Response<User>) => {const newUser = req.body;users.push(newUser);res.status(201).json(newUser);
});const PORT = 3000;
app.listen(PORT, () => {console.log(`Server running on http://localhost:${PORT}`);
});
12. 测试与调试
Jest + TypeScript:
// math.test.ts
import { add, subtract } from './math';describe('math functions', () => {it('should add two numbers', () => {expect(add(1, 2)).toBe(3);});it('should subtract two numbers', () => {expect(subtract(5, 3)).toBe(2);});
});// math.ts
export function add(a: number, b: number): number {return a + b;
}export function subtract(a: number, b: number): number {return a - b;
}
13. 高级配置与优化
tsconfig.json 详解:
{"compilerOptions": {"target": "es6", // 编译目标版本"module": "commonjs", // 模块系统"strict": true, // 启用所有严格类型检查选项"esModuleInterop": true, // 兼容 CommonJS 和 ES Modules"skipLibCheck": true, // 跳过声明文件的类型检查"forceConsistentCasingInFileNames": true, // 强制文件名大小写一致"outDir": "./dist", // 输出目录"rootDir": "./src", // 源文件目录"baseUrl": ".", // 解析非相对模块的基础目录"paths": { // 路径映射"@/*": ["src/*"]},"declaration": true, // 生成 .d.ts 声明文件"sourceMap": true // 生成 source map},"include": ["src/**/*"],"exclude": ["node_modules", "**/*.spec.ts"]
}
14. 性能优化与最佳实践
-
使用 const 断言:
const colors = ["red", "green", "blue"] as const;
-
避免 any 类型:
// 不好 function logValue(val: any) {console.log(val); }// 好 function logValue<T>(val: T) {console.log(val); }
-
使用类型守卫:
function isString(test: any): test is string {return typeof test === "string"; }
-
合理使用 unknown 类型:
function safeParse(json: string): unknown {return JSON.parse(json); }
-
使用实用类型:
interface User {id: number;name: string;age: number; }type PartialUser = Partial<User>; // 所有属性可选 type ReadonlyUser = Readonly<User>; // 所有属性只读 type UserWithoutAge = Omit<User, 'age'>; // 排除 age 属性