TypeScript 语法速查 - 码剑客

TypeScript 语法速查:基础与字面量类型、interface 与 type 取舍、泛型约束、条件类型与 infer、常用工具类型,以及 tsconfig 严格配置与 tsc、tsx 命令行用法。

TypeScript 5.x更新于 2026-10-30共 23 条

基础类型

原始类型注解,多数场景可由赋值自动推断,无需手写

let name: string = 'web'
let port: number = 8080
let ok: boolean = true

unknown 必须先收窄类型才能使用,比 any 安全

let input: unknown = JSON.parse(raw)
if (typeof input === 'string') input.trim()

never 表示永不正常返回,适合抛错函数与穷尽性检查

function fail(msg: string): never {
  throw new Error(msg)
}

字面量联合限制取值,交叉类型可模拟品牌类型做更严格的 ID 校验

type Env = 'dev' | 'prod'
type Id = string & { readonly brand: unique symbol }

as 强制断言不改运行时行为;satisfies 校验类型同时保留更精确的推断

const value = config as AppConfig
const safe = obj satisfies AppConfig

对象与函数

interface 适合描述对象结构且可声明合并,? 为可选、readonly 为只读

interface User {
  id: string
  name?: string
  readonly email: string
}

type 适合联合、交叉与函数别名,不能被声明合并

type Point = { x: number; y: number }
type Handler = (event: Event) => void

索引签名描述动态键;已知键更推荐用 Record<string, number>

interface Dict {
  [key: string]: number
}

函数重载先声明多个签名,再由实现统一处理

function parse(input: string): string
function parse(input: number): number
function parse(input: string | number) {
  return typeof input === 'string' ? input.trim() : input
}

泛型约束保证传入类型具备所需字段,返回值仍保留原始类型

function first<T extends { id: string }>(items: T[]): T | undefined {
  return items[0]
}

高级类型

keyof 取键的联合,typeof 取值的类型

type Keys = keyof User
type UserType = typeof defaultUser

映射类型批量改造属性,可配合 -? 或 +readonly 调整修饰符

type Optional<T> = { [K in keyof T]?: T[K] }

条件类型配合 infer 从数组中提取元素类型

type ElementType<T> = T extends (infer U)[] ? U : never

工具类型组合可精确描述局部更新与投影,避免重复定义接口

type Patch = Partial<Pick<User, 'name' | 'email'>>
type Summary = Omit<User, 'email'>
type Map = Record<string, number>

从函数取返回类型、从类取实例类型,是二次封装库的常用写法

type Return<T> = T extends (...args: never[]) => infer R ? R : never
class Store {}
type StoreInstance = InstanceType<typeof Store>

tsconfig 配置

strict 打开全部严格检查,noUncheckedIndexedAccess 让索引访问返回可能 undefined

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}

target 决定语法降级程度,lib 决定可用的内置类型声明

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "lib": ["ES2022", "DOM"]
  }
}

路径别名只影响类型解析,运行时还需构建工具同步配置相同别名

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": { "@/*": ["src/*"] }
  }
}

skipLibCheck 跳过依赖包声明检查,可显著加快大型项目类型检查

{
  "compilerOptions": {
    "strict": true,
    "skipLibCheck": true
  }
}

命令行与迁移

生成 tsconfig.json 模板,按需裁剪注释与选项

npx tsc --init

只做类型检查不产出文件,适合接入 CI 与 lint 阶段

npx tsc --noEmit

直接运行 TS 脚本,tsx 比 ts-node 更快且默认支持 ESM

npx tsx scripts/build.ts

为缺少类型声明的模块补充声明,写法放在 .d.ts 文件中

declare module '*.vue' {
  const component: DefineComponent<{}, {}, any>
  export default component
}

本网站使用 Cookie 以确保您在我们的网站上获得最佳体验。 隐私政策.