Skip to content

TypeScript 基础

作者: luote (luote) · 个人主页 luote996.cn

为什么前端用 TypeScript

JavaScript 运行灵活但缺少编译期类型检查,大型项目容易因拼写错误、字段缺失导致运行时 bug。TypeScript(TS)是 JavaScript 的超集,增加 静态类型,在 vue-tsc 编译阶段就能发现问题。create-luote 前端全面使用 TS。

基本类型

typescript
let count: number = 0
let title: string = 'luote'
let loading: boolean = false
let ids: number[] = [1, 2, 3]

函数参数与返回值也可标注类型:

typescript
function add(a: number, b: number): number {
  return a + b
}

接口 interface

描述对象结构,与后端 VO/DTO 对应:

typescript
export interface UserVO {
  id: number
  username: string
  nickname?: string  // 可选字段
}

export interface LoginResult {
  token: string
  user: UserVO
}

脚手架 src/api/types.ts 集中定义 API 相关类型,各模块 import 复用。

类型别名 type

typescript
export type ApiResult<T> = {
  code: number
  message: string
  data: T
}

typeinterface 多数场景可互换;联合类型常用 type

typescript
type Status = 'idle' | 'loading' | 'error'

泛型

泛型让类型随参数变化,如统一响应:

typescript
function unwrap<T>(res: ApiResult<T>): T {
  if (res.code !== 200) {
    throw new Error(res.message)
  }
  return res.data
}

Axios 封装里 request.get<UserVO>('/users/me') 即指定响应 data 类型。

在 Vue 组件中使用

vue
<script setup lang="ts">
import { ref } from 'vue'
import type { UserVO } from '@/api/types'

const user = ref<UserVO | null>(null)
</script>

ref<UserVO | null> 表示 user 可能是 null,访问前需判断,避免运行时错误。

模块导入导出

typescript
// types.ts
export interface UserVO { ... }

// user.ts
import type { UserVO } from './types'
import { get } from './request'

export function fetchMe() {
  return get<UserVO>('/users/me')
}

import type 仅导入类型,编译后会被擦除,不影响打包体积。

与 JavaScript 的差异(简要)

特性TSJS
类型编译期检查
枚举 enum支持无原生 enum
访问修饰符类中 public/privateES2022 有 # 私有字段

Vue 单文件组件 <script setup lang="ts"> 中可直接写 TS,无需额外配置。

与 luote 脚手架的关系

文件说明
src/api/types.ts公共类型定义
src/api/request.ts泛型封装 get/post
tsconfig.json编译选项、路径别名 @
vite-env.d.tsVite 环境变量类型 VITE_*

下一章:Vue 3 基础

MIT Licensed