TS学习指南
一、TypeScript 简介
TypeScript (TS) 是 JavaScript 的超集,添加了静态类型系统和现代语法特性,适用于大型项目开发。核心优势:
-
类型安全:编译时类型检查,减少运行时错误。
-
代码提示:IDE 智能提示提升开发效率。
-
代码可维护性:显式类型声明增强代码可读性。
二、环境配置
1. 安装 TypeScript
npm install -g typescript # 全局安装(推荐) npm install typescript --save-dev # 本地安装
2. 初始化项目
tsc --init # 生成 tsconfig.json
3. 编译 TypeScript
tsc # 编译所有 .ts 文件 tsc -w # 监听文件变化并自动编译
三、基础语法
1. 类型注解
// 基本类型 let name: string = "Alice"; let age: number = 30; let isActive: boolean = true; let data: any = "任意类型";// 数组 let numbers: number[] = [1, 2, 3]; let mixed: (string | number)[] = ["a", 1];// 对象 type User = {id: number;name: string;email?: string; // 可选属性 }; const user: User = { id: 1, name: "Bob" };// 函数 function add(a: number, b: number): number {return a + b; } const greet = (name: string): void => console.log(`Hello, ${name}`);
2. 接口 (Interface)
interface Product {id: number;name: string;price: number;getDescription(): string; }const product: Product = {id: 1,name: "Laptop",price: 999,getDescription() {return `${this.name} - $${this.price}`;} };
3. 类型别名 (Type Alias)
type Point = {x: number;y: number; };type ID = string | number;
4. 泛型 (Generics)
function identity<T>(arg: T): T {return arg; } const output = identity<string>("hello");// 泛型约束 interface Lengthwise {length: number; } function loggingIdentity<T extends Lengthwise>(arg: T): T {console.log(arg.length);return arg; }
5. 枚举 (Enum)
enum Direction {Up = "UP",Down = "DOWN", } const move = (dir: Direction) => console.log(dir); move(Direction.Up);
四、高级特性
1. 类型推断与断言
// 类型推断 let score = 100; // 自动推断为 number// 类型断言 const input = document.getElementById("input") as HTMLInputElement; const value = (input as unknown) as number; // 双重断言(慎用)
2. 联合类型与交叉类型
type Admin = { role: "admin" }; type User = { role: "user" };// 联合类型 type Person = Admin | User;// 交叉类型 type Named = { name: string }; type Aged = { age: number }; type PersonProfile = Named & Aged;
3. 类型守卫 (Type Guards)
function isString(value: any): value is string {return typeof value === "string"; }const processValue = (value: string | number) => {if (isString(value)) {console.log(value.toUpperCase());} else {console.log(value.toFixed(2));} };
4. 索引签名与映射类型
// 索引签名 interface StringArray {[index: number]: string; }// 映射类型 type ReadonlyProduct = Readonly<Product>; type PartialProduct = Partial<Product>;
五、在 Vue 项目中使用 TypeScript
1. 创建 Vue + TypeScript 项目
npm create vue@latest # 选择 TypeScript 支持
2. 单文件组件 (SFC) 写法
<script setup lang="ts"> import { ref } from 'vue';// 类型化 Props interface Props {title: string;count?: number; } const props = defineProps<Props>();// 类型化响应式数据 const counter = ref<number>(0);// 类型化事件 const emit = defineEmits<{(e: 'update', value: number): void; }>(); </script><template><h1>{{ title }}</h1><button @click="counter++">{{ counter }}</button> </template>
3. 组合式 API (Composition API)
import { computed, reactive } from 'vue';interface User {name: string;age: number; }const user = reactive<User>({ name: "Alice", age: 30 }); const isAdult = computed(() => user.age >= 18);
4. 第三方库类型支持
npm install @types/lodash --save-dev # 安装 Lodash 类型声明
六、工程化配置
1. tsconfig.json
关键配置
{"compilerOptions": {"target": "ES2020", // 编译目标版本"module": "ESNext", // 模块系统"strict": true, // 启用严格类型检查"esModuleInterop": true, // 兼容 CommonJS/ESM"skipLibCheck": true, // 跳过库类型检查"moduleResolution": "node","baseUrl": "./","paths": {"@/*": ["src/*"] // 路径别名}},"include": ["src/**/*.ts", "src/**/*.vue"] }
2. 与构建工具集成
-
Vite: 内置 TypeScript 支持,无需额外配置。
-
Webpack: 使用
ts-loader
:// webpack.config.js module.exports = {module: {rules: [{test: /\.tsx?$/,use: 'ts-loader',exclude: /node_modules/,},],}, };
七、调试与测试
1. 调试配置 (VS Code)
// .vscode/launch.json {"version": "0.2.0","configurations": [{"type": "chrome","request": "launch","name": "Debug Vue","url": "http://localhost:3000","webRoot": "${workspaceFolder}/src"}] }
2. 单元测试 (Vitest)
// tests/example.spec.ts import { describe, it, expect } from 'vitest'; import { add } from '../src/utils';describe('add function', () => {it('should return 3 when inputs are 1 and 2', () => {expect(add(1, 2)).toBe(3);}); });
八、注意事项
-
优先使用
interface
:
定义对象形状时优先用接口,需要联合类型或元组时用type
。 -
避免
any
:
使用unknown
替代any
,必要时通过类型断言明确类型。 -
类型文件管理:
全局类型定义放在src/types
目录,模块类型就近定义。 -
类型声明文件 (
*.d.ts
):
为第三方库补充类型声明:// src/types/shims.d.ts declare module "*.vue" {import { DefineComponent } from "vue";const component: DefineComponent<{}, {}, any>;export default component; }
九、常见问题
-
类型声明缺失:
使用@types
包或手动声明:declare module 'untyped-library' {export function doSomething(): void; }
-
类型推断错误:
使用// @ts-ignore
临时忽略错误,或优化类型定义。 -
Vue 模板类型检查:
使用 Volar 插件(替代 Vetur)获得更好的模板类型支持。