TypeScript 简介
TypeScript 是 JavaScript 的超集,为 JavaScript 添加了静态类型定义。它让大型项目更容易维护,减少了运行时错误。
基本配置
1. 初始化 TypeScript 项目
1 2 3 4 5
| npm install -g typescript
tsc --init
|
2. 推荐的 tsconfig.json 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| { "compilerOptions": { "target": "ES2020", "lib": ["DOM", "DOM.Iterable", "ES2020"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "baseUrl": ".", "paths": { "@/*": ["./src/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
|
类型定义实践
1. 基础类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| let isDone: boolean = false; let decimal: number = 6; let color: string = "blue";
let list: number[] = [1, 2, 3]; let listGeneric: Array<number> = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];
enum Color { Red, Green, Blue, } let c: Color = Color.Green;
|
2. 接口和类型别名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| interface User { id: number; name: string; email: string; age?: number; readonly createdAt: Date; }
type Point = { x: number; y: number; };
type Status = "pending" | "success" | "error";
type Employee = Person & Company;
|
高级配置
1. 路径别名配置
1 2 3 4 5 6 7 8 9 10 11
| { "compilerOptions": { "baseUrl": ".", "paths": { "@components/*": ["src/components/*"], "@utils/*": ["src/utils/*"], "@types/*": ["src/types/*"] } } }
|
2. ESLint 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| { "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "rules": { "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/explicit-function-return-type": [ "warn", { "allowExpressions": true } ] } }
|
项目结构建议
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| project/ ├── src/ │ ├── components/ # 组件 │ ├── pages/ # 页面组件 │ ├── utils/ # 工具函数 │ ├── types/ # 类型定义 │ ├── hooks/ # 自定义 Hooks │ ├── services/ # API 服务 │ └── styles/ # 样式文件 ├── public/ # 静态资源 ├── tests/ # 测试文件 ├── .eslintrc.json # ESLint 配置 ├── .prettierrc # Prettier 配置 ├── tsconfig.json # TypeScript 配置 └── package.json # 项目依赖
|
常见问题解决
1. 模块导入问题
1 2 3 4 5 6 7 8 9 10
| declare module "*.png" { const value: string; export default value; }
declare module "*.svg" { const value: React.FC<React.SVGProps<SVGSVGElement>>; export default value; }
|
2. 第三方库类型缺失
1 2 3 4
| npm install --save-dev @types/react npm install --save-dev @types/react-dom npm install --save-dev @types/node
|
总结
TypeScript 是现代前端开发的标配,合理的配置能够显著提升开发效率和代码质量。建议从项目开始就使用 TypeScript,逐步掌握其高级特性。
下一步学习: