当前位置: 首页 > news >正文

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);});
});

八、注意事项
  1. 优先使用 interface
    定义对象形状时优先用接口,需要联合类型或元组时用 type

  2. 避免 any
    使用 unknown 替代 any,必要时通过类型断言明确类型。

  3. 类型文件管理
    全局类型定义放在 src/types 目录,模块类型就近定义。

  4. 类型声明文件 (*.d.ts)
    为第三方库补充类型声明:

    // src/types/shims.d.ts
    declare module "*.vue" {import { DefineComponent } from "vue";const component: DefineComponent<{}, {}, any>;export default component;
    }

九、常见问题
  1. 类型声明缺失
    使用 @types 包或手动声明:

    declare module 'untyped-library' {export function doSomething(): void;
    }
  2. 类型推断错误
    使用 // @ts-ignore 临时忽略错误,或优化类型定义。

  3. Vue 模板类型检查
    使用 Volar 插件(替代 Vetur)获得更好的模板类型支持。

http://www.xdnf.cn/news/220861.html

相关文章:

  • 人工智能和机器学习在包装仿真中的应用与价值
  • MQTT - Android MQTT 编码实战(MQTT 客户端创建、MQTT 客户端事件、MQTT 客户端连接配置、MQTT 客户端主题)
  • Python列表全面解析:从基础到高阶操作
  • 域名转移:什么是转移码/EPP码/授权码?
  • 基于蓝耘MaaS平台进行api调用创建本地智能ai
  • 代码随想录第39天|leetcode198.打家劫舍、leetcode213.打家劫舍II 、leetcode337.打家劫舍III
  • 4月29日日记
  • 【浙江大学DeepSeek公开课】DeepSeek的本地化部署与AI通识教育之未来
  • 高等数学-第七版-下册 选做记录 习题9-5
  • 【记】Laya2.x数字末尾导致换行异常问题
  • Promtail+Loki+Grafana监控日志
  • AD系列:Windows Server 2025 搭建AD域控和初始化
  • 一文读懂 JavaScript 中的深浅拷贝
  • IEC61499编程方式与传统PLC编程方式比较
  • 生态修复项目管理软件
  • RPCRT4!NdrpEmbeddedPointerMemorySize函数分析之第二次循环
  • 应急演练考试排查-WebSever03
  • P5633 最小度限制生成树
  • Linux环境变量以及进程虚拟地址原理
  • DVWA靶场保姆级通关教程---02命令注入
  • 5.4.2 MVVM例2-用户控件的使用(水在水管中流动的实例)
  • 路径规划算法总结:从 Dijkstra 到 A* 与 Hybrid A
  • GUI_DrawPixel 函数详解
  • BalenaEtcher 2.1镜像烧录工具软件下载及安装教程
  • Vite性能优化指南 ✅
  • 强化学习(二)马尔科夫决策过程(MDP)
  • java AsyncTool
  • ACTF2025 - WEB Excellent-Site
  • 第十章:CrewAI - 面向流程的多 Agent 结构化协作
  • Andorid车机UI适配,AndroidUI图px的单位,如何适配1920x720,PPI100的屏幕设备