Featured image of post TypeScript

TypeScript

TypeScript 学习指南

前言

本文为想系统学习 TypeScript 的前端开发者准备,覆盖从基础类型、配置、进阶类型到在 Vue 项目中使用 TypeScript 的简单实战示例。

1. 为什么学 TypeScript

  • 静态类型可以在编译期发现很多常见错误,提高代码可维护性。
  • 与现代 IDE(例如 VS Code)结合,能获得更好的智能提示、重构支持和文档提示。

2. 快速开始

1
2
3
4
# 初始化项目
pnpm init -y
pnpm add -D typescript
npx tsc --init

这会生成 tsconfig.json

一个常见的 tsconfig.json 最小配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
	"compilerOptions": {
		"target": "ES2020",
		"module": "ESNext",
		"moduleResolution": "Node",
		"strict": true,
		"jsx": "preserve",
		"esModuleInterop": true,
		"skipLibCheck": true,
		"forceConsistentCasingInFileNames": true
	}
}

3. 基础类型示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 原始类型
let s: string = 'hello'
let n: number = 123
let b: boolean = true

// 数组与元组
let arr: number[] = [1,2,3]
let tup: [string, number] = ['age', 18]

// 联合类型与类型别名
type ID = string | number
let id: ID = 'abc'

// 接口与类型
interface User { id: ID; name: string }
const user: User = { id: 'u1', name: 'Alice' }

// 函数类型
function add(a: number, b: number): number { return a + b }

4. 进阶类型

  • 泛型(Generics)
  • 映射类型(Mapped Types)
  • 条件类型(Conditional Types)

泛型示例:

1
2
function identity<T>(arg: T): T { return arg }
const s = identity<string>('hi')

5. 在 Vue 中使用 TypeScript

  • 推荐使用 script setup lang="ts"
  • 在 Vite + Vue 项目中,shims-vue.d.ts 可能需要声明 Vue 文件支持:
1
2
3
4
5
declare module '*.vue' {
	import { DefineComponent } from 'vue'
	const component: DefineComponent<{}, {}, any>
	export default component
}

组件示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<script setup lang="ts">
import { defineProps } from 'vue'

interface Props { title: string }
const props = defineProps<Props>()
</script>

<template>
	<h1>{{ props.title }}</h1>
</template>

6. 常见模式与技巧

  • 使用 as const 固定字面量类型。
  • 使用 unknown 代替 any 做更严格的类型收敛。
  • 使用 ReturnType<>, Partial<>, Required<> 等工具类型提高复用性。

7. 配合工具链

  • ESLint 与 TypeScript: 使用 @typescript-eslint/parser@typescript-eslint/eslint-plugin
  • 编辑器:确保安装 TypeScript 相关插件并在项目中使用本地 TypeScript(避免全局版本不一致)。

8. 练习任务

  1. 把一个小型 JS 项目迁移到 TypeScript(从 --strict 放宽到逐步开启 strict 规则)。
  2. 写一个简单的泛型工具函数并写测试(Vitest)。

9. 参考资源

Licensed under CC BY-NC-SA 4.0