TypeScript知识速览

TypeScript知识速览

文章目录


核心概念

是什么

  • JavaScript的超集(Superset)
  • 微软开发,2012年发布
  • 编译后生成纯JavaScript
  • 静态类型检查系统

核心优势

  • 静态类型检查(编译时发现错误)
  • 强大的IDE支持(智能提示/重构)
  • 更易于维护和协作
  • 最新JS特性提前使用
  • 企业级项目首选

编译流程

  • .ts 源文件 → TypeScript编译器(tsc) → .js 目标文件
  • 配置:tsconfig.json

基础类型系统

原始类型

  • string(字符串)
  • number(数字,含整数/浮点)
  • boolean(布尔)
  • null / undefined
  • symbol / bigint

特殊类型

  • any(任意类型,慎用)
  • unknown(未知类型,安全版any)
  • never(永不返回,如抛出异常)
  • void(无返回值)

类型推断

  • 自动推断变量类型
  • let name = "ts" → 推断为string

复杂类型

数组与元组

  • 数组:number[] 或 Array<number>
  • 元组:[string, number](固定长度+类型)

对象类型

  • 接口(Interface)
    • interface Person { name: string; age: number }
  • 类型别名(Type Alias)
    • type Person = { name: string; age: number }
  • 可选属性:age?: number
  • 只读属性:readonly id: number

联合与交叉类型

  • 联合类型(Union):string | number(或)
  • 交叉类型(Intersection):A & B(且)

枚举(Enum)

  • 数字枚举:enum Color { Red, Green, Blue }
  • 字符串枚举:enum Status { Success = "OK" }
  • 常量枚举:const enum

函数类型

函数声明

  • 参数类型:function add(x: number, y: number): number
  • 箭头函数:const add = (x: number, y: number): number => x + y

可选与默认参数

  • 可选:function fn(x?: number)
  • 默认:function fn(x: number = 10)

剩余参数与重载

  • 剩余参数:function fn(...args: number[])
  • 函数重载:同名函数不同参数类型

高级类型

类型断言

  • 角度括号:<string>someVar
  • as语法:someVar as string(推荐,JSX兼容)

类型保护

  • typeof判断:typeof x === "string"
  • instanceof判断:x instanceof Date
  • 自定义类型守卫:function isString(x): x is string

泛型(Generics)

  • 基础泛型:function identity<T>(arg: T): T
  • 泛型约束:<T extends { length: number }>
  • 泛型接口/类

映射类型

  • Partial<T>(所有属性可选)
  • Required<T>(所有属性必选)
  • Readonly<T>(所有属性只读)
  • Pick<T, K>(选取部分属性)
  • Omit<T, K>(省略部分属性)
  • Record<K, T>(构造对象类型)

类与面向对象

类基础

  • 属性/方法修饰符:public(默认)/private/protected/readonly
  • 构造函数:constructor(public name: string)
  • 继承:class Child extends Parent
  • 抽象类:abstract class

接口实现

  • class MyClass implements MyInterface

访问器

  • getter/setter:get name() / set name(value)

模块系统

导入导出

  • 导出:export / export default
  • 导入:import { x } from "./module" / import * as mod
  • 类型导入:import type { MyType }

模块解析

  • 相对路径:./ / .../
  • 非相对路径:基于baseUrl/paths配置

类型声明

声明文件(.d.ts)

  • 为JS库提供类型声明
  • declare关键字:declare function jQuery(selector: string): any

第三方声明

  • @types组织:npm install @types/node
  • 三斜线指令:/// <reference types="node" />

配置文件

tsconfig.json核心选项

  • compilerOptions
    • target:编译目标ES版本(ES5/ES6/ES2020)
    • module:模块系统(CommonJS/ESNext)
    • strict:严格模式总开关
    • esModuleInterop:ES模块互操作
    • skipLibCheck:跳过声明文件检查
    • outDir:输出目录
    • rootDir:源码目录
  • include/exclude:文件包含/排除

严格模式选项

  • strictNullChecks(null/undefined检查)
  • noImplicitAny(禁止隐式any)
  • strictFunctionTypes(函数参数严格逆变)

实用工具类型

内置工具类型

  • ReturnType<T>(提取函数返回类型)
  • Parameters<T>(提取函数参数类型)
  • NonNullable<T>(排除null/undefined)
  • Exclude<T, U>(从T中排除U)
  • Extract<T, U>(提取T中可赋值给U的类型)

条件类型

  • T extends U ? X : Y

常见模式与技巧

类型别名 vs 接口

  • 接口:可合并声明(声明合并),适合对象
  • 类型别名:可表达联合/交叉,适合复杂类型

常量断言

  • as const:将对象转为只读字面量类型

类型推导助手

  • typeof操作符获取变量类型
  • keyof获取对象键的联合类型
  • in遍历联合类型

与JavaScript关系

兼容策略

  • 有效JS代码就是有效TS代码(默认)
  • 渐进式迁移:从宽松配置开始
  • .js文件类型检查:allowJs/checkJs

编译目标

  • 可编译为ES3/5/6/Next
  • 支持各种模块系统

开发工具

编辑器支持

  • VS Code(原生最佳支持)
  • WebStorm/Vim/Neovim

构建工具

  • tsc(官方编译器)
  • Webpack/Vite/Rollup(打包器+ts-loader/esbuild)
  • Babel(@babel/preset-typescript)

类型检查

  • tsc --noEmit(仅类型检查,不输出文件)
  • tsc --watch(监视模式)
相关推荐
wgod几秒前
new AbortController()
前端
UXbot6 分钟前
UXbot 是什么?一句指令生成完整应用的 AI 工具
前端·ai·交互·个人开发·ai编程·原型模式·ux
棒棒的唐21 分钟前
WSL2用npm安装的openclaw,无法正常使用openclaw gateway start启动服务的问题
前端·npm·gateway
哔哩哔哩技术30 分钟前
使用Compose Navigation3进行屏幕适配
前端
:mnong1 小时前
Claude Code 项目设计分析
typescript·claude code
Z_Wonderful1 小时前
在 Next.js 中,使用 [id] 或 public 作为文件夹或文件名是两种完全不同的概念,分别对应 动态路由 和 静态资源托管
javascript·网络·chrome
咬人喵喵1 小时前
E2.COOL 平台深度解析:从特效分类到实战操作指南
前端·编辑器·svg
RisunJan2 小时前
Linux命令-named-checkzone
linux·前端
小陈工2 小时前
Python Web开发入门(十):数据库迁移与版本管理——让数据库变更可控可回滚
前端·数据库·人工智能·python·sql·云原生·架构
吹晚风吧2 小时前
解决vite打包,base配置前缀,nginx的dist包找不到资源
服务器·前端·nginx