TypeScript 学习指南

TypeScript 学习指南

📚 目录

  • 一、基础类型与变量
    • [1. 基本类型](#1. 基本类型 "#1-%E5%9F%BA%E6%9C%AC%E7%B1%BB%E5%9E%8B")
    • [2. 类型别名与接口](#2. 类型别名与接口 "#2-%E7%B1%BB%E5%9E%8B%E5%88%AB%E5%90%8D%E4%B8%8E%E6%8E%A5%E5%8F%A3")
  • 二、类型系统核心能力
    • [3. 联合类型(Union Types)](#3. 联合类型(Union Types) "#3-%E8%81%94%E5%90%88%E7%B1%BB%E5%9E%8Bunion-types")
    • [4. 交叉类型(Intersection Types)](#4. 交叉类型(Intersection Types) "#4-%E4%BA%A4%E5%8F%89%E7%B1%BB%E5%9E%8Bintersection-types")
    • [5. 类型推断与类型断言](#5. 类型推断与类型断言 "#5-%E7%B1%BB%E5%9E%8B%E6%8E%A8%E6%96%AD%E4%B8%8E%E7%B1%BB%E5%9E%8B%E6%96%AD%E8%A8%80")
    • [6. 映射类型(Mapped Types)](#6. 映射类型(Mapped Types) "#6-%E6%98%A0%E5%B0%84%E7%B1%BB%E5%9E%8Bmapped-types")
    • [7. 条件类型与 infer](#7. 条件类型与 infer "#7-%E6%9D%A1%E4%BB%B6%E7%B1%BB%E5%9E%8B%E4%B8%8E-infer")
    • [8. 类型守卫(Type Guards)](#8. 类型守卫(Type Guards) "#8-%E7%B1%BB%E5%9E%8B%E5%AE%88%E5%8D%ABtype-guards")
  • 三、泛型与高级类型工具
    • [9. 泛型(Generics)](#9. 泛型(Generics) "#9-%E6%B3%9B%E5%9E%8Bgenerics")
    • [10. 常用泛型工具类型](#10. 常用泛型工具类型 "#10-%E5%B8%B8%E7%94%A8%E6%B3%9B%E5%9E%8B%E5%B7%A5%E5%85%B7%E7%B1%BB%E5%9E%8B")
  • 四、应用进阶
    • [11. 字符串字面量类型与模板字面量类型](#11. 字符串字面量类型与模板字面量类型 "#11-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AD%97%E9%9D%A2%E9%87%8F%E7%B1%BB%E5%9E%8B%E4%B8%8E%E6%A8%A1%E6%9D%BF%E5%AD%97%E9%9D%A2%E9%87%8F%E7%B1%BB%E5%9E%8B")
    • [12. 可辨识联合与索引类型](#12. 可辨识联合与索引类型 "#12-%E5%8F%AF%E8%BE%A8%E8%AF%86%E8%81%94%E5%90%88%E4%B8%8E%E7%B4%A2%E5%BC%95%E7%B1%BB%E5%9E%8B")
    • [13. this 类型与流式接口](#13. this 类型与流式接口 "#13-this-%E7%B1%BB%E5%9E%8B%E4%B8%8E%E6%B5%81%E5%BC%8F%E6%8E%A5%E5%8F%A3")
    • [14. 可选链与空值合并运算符](#14. 可选链与空值合并运算符 "#14-%E5%8F%AF%E9%80%89%E9%93%BE%E4%B8%8E%E7%A9%BA%E5%80%BC%E5%90%88%E5%B9%B6%E8%BF%90%E7%AE%97%E7%AC%A6")
  • 五、总结&学习建议

一、基础类型与变量

1. 基本类型

概念说明:

TypeScript 拥有丰富的基础类型:number、string、boolean、array、tuple、enum、any、void、null、undefined、never 和 unknown 等。

  • number:表示所有数字,包括整数和浮点数。如:

    typescript 复制代码
    let n: number = 42;
  • string:字符串类型,表示文本数据。如:

    typescript 复制代码
    let s: string = "hello";```
  • boolean:布尔类型,只能是 truefalse。如:

    typescript 复制代码
    let flag: boolean = true;
  • array:数组类型,同类型元素的有序集合。如:

    typescript 复制代码
    let arr: number[] = [1, 2, 3];
  • tuple(元组):固定长度、各元素类型可不同的数组。如:

    typescript 复制代码
    let pair: [string, number] = ['foo', 1];
  • enum:枚举类型,用于定义一组命名常量。如:

    typescript 复制代码
    enum Color {
      Red,
      Green,
      Blue,
    }
    let c: Color = Color.Green;
  • any:任意类型,关闭类型检查,谨慎使用。如:

    typescript 复制代码
    let anything: any = 123;
  • void:通常用于函数无返回值。

    typescript 复制代码
    function log(): void {
      console.log('hi');
    }
  • nullundefined:分别表示空值和未定义。可以赋给任意类型,但需要严格模式下注意区别。

  • never:表示不会有值的类型,如函数抛异常或死循环时的返回值:

    typescript 复制代码
    function error(msg: string): never {
      throw new Error(msg);
    }
  • unknown:类型安全的 any,只能经过类型检查后才能赋值给其他类型。用于安全接收不确定类型的数据。

    typescript 复制代码
    let value: unknown = 123;
    if (typeof value === 'string') {
      console.log(value.length); // 类型收窄后才能访问 string 的属性
    }

TypeScript 默认为严格区分 nullundefined,配置项 strictNullChecks 开启时变量不会默认包含这两者,需单独指定。

2. 类型别名与接口

概念说明:

  • 类型别名(type)可以为任何类型(基本类型、联合、对象、元组等)起别名。
  • 接口(interface)主要用于描述对象、函数、类的结构。

类型别名(type)与接口(interface)对比:

type interface
定义对象类型
定义基本/联合/元组类型 ❌(只能描述对象、类、函数结构)
扩展(继承) 通过 & 交叉类型合成 extends 关键字继承、交叉合成
重新打开/声明合并 ❌(不可重复定义) ✅(多次声明自动合并同名 interface)
实现类 ✅(class implements interface)
推荐场景 复杂类型、组合类型、多种类型联合 主要用于对象结构、面向对象接口

使用建议: 对象结构建议优先用 interface,涉及联合、交叉或基础类型的组合、类型工具一般用 type。

简单对比代码:

使用 type

typescript 复制代码
// 使用 type
type PointOrId = { x: number; y: number } | number;
type Name = string;

使用 interface

typescript 复制代码
// 定义Person
interface Person {
  name: string;
  age: number;
}
// 合并接口
interface Person {
  gender?: string;
}
const tom: Person = { name: 'Tom', age: 20, gender: 'male' };

// 接口可继承
interface Student extends Person {
  studentId: number;
}
const alice: Student = {
  name: 'Alice',
  age: 21,
  gender: 'female',
  studentId: 1001,
};
// 实现类
class Teacher implements Person {
  name: string;
  age: number;
  gender?: string;
  subject: string;
  constructor(name: string, age: number, subject: string, gender?: string) {
    this.name = name;
    this.age = age;
    this.subject = subject;
    if (gender) {
      this.gender = gender;
    }
  }
}
const msSmith = new Teacher('Smith', 35, 'Math', 'female');

二、类型系统核心能力

3. 联合类型(Union Types)

概念说明:

联合类型用 | 分隔,表示一个值可以是多种类型之一,对应多种可能取值场景。

示例:

typescript 复制代码
function printId(id: string | number) {
  if (typeof id === 'string') {
    console.log(id.toUpperCase());
  } else {
    console.log(id);
  }
}

4. 交叉类型(Intersection Types)

概念说明:

交叉类型用 &,把多个类型的所有特性组合在一起(多重继承)。

示例:

typescript 复制代码
type Person = { name: string };
type Employee = { id: number };
type Staff = Person & Employee;
let staff: Staff = { name: 'Mike', id: 101 };

5. 类型推断与类型断言

类型推断

TypeScript 能自动推断变量类型。

类型断言

类型断言用于确定变量的具体类型(通常用 as)。有时候你比 TypeScript 更了解某个值的类型,可以使用类型断言。

示例:

typescript 复制代码
let num = 4; // 推断为 number

let someValue: any = 'some text';
let len: number = (someValue as string).length;

6. 映射类型(Mapped Types)

概念说明:

映射类型可对已有类型做结构变换,自动化构造新类型结构(如批量只读、可选)。

示例:

typescript 复制代码
type Readonly<T> = {
  readonly [K in keyof T]: T[K];
};
type Person = { name: string; age: number };
type ReadonlyPerson = Readonly<Person>; // name、age只读

7. 条件类型与 infer

概念说明:

  • 条件类型允许根据类型逻辑做分支推导。
  • infer 可在条件类型内做类型局部推断。

示例:

typescript 复制代码
type IsString<T> = T extends string ? true : false;
type A = IsString<'abc'>; // true

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
function fn(x: number): string {
  return x.toString();
}
type FnReturn = ReturnType<typeof fn>; // string

8. 类型守卫(Type Guards)

概念说明:

类型守卫让类型缩小到更具体的类型,提升类型安全性(典型如 typeof、instanceof、自定义守卫函数)。

示例:

typescript 复制代码
function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function example(val: string | number) {
  if (isString(val)) {
    // val 被收窄为 string
    console.log(val.toUpperCase());
  }
}

function printId(id: string | number) {
  if (typeof id === 'string') {
    console.log('String id:', id.toUpperCase());
  } else {
    console.log('Number id:', id);
  }
}

三、泛型与高级类型工具

9. 泛型(Generics)& 索引签名(Index Signature)

泛型:

泛型为类型参数化,允许类型灵活支持多种场景。

示例:

typescript 复制代码
function identity<T>(arg: T): T {
  return arg;
}

let num = identity<number>(1); // num: number
let txt = identity<string>('hi'); // txt: string

索引签名: 索引签名用于定义对象可以有任意数量的某种类型的属性名和值。

示例:

typescript 复制代码
interface StringMap {
  [key: string]: string;
}

const dict: StringMap = {
  hello: '你好',
  world: '世界',
};

你也可以限定值为其它类型,并且 number 形式的索引会被转为 string

typescript 复制代码
interface NumberMap {
  [key: number]: boolean;
}

const status: NumberMap = {
  1: true,
  2: false,
};
// 实际等价于 { '1': true, '2': false }

10. 常用泛型工具类型

概念说明: TypeScript 标准库内置多种泛型类型工具,极大增强类型复用性和便捷性。

  • Partial<T>:所有属性变为可选
  • Required<T>:所有属性变为必填
  • Readonly<T>:所有属性只读
  • Pick<T, K>:保留指定属性
  • Omit<T, K>:去除指定属性
  • Record<K,T>:构造以 K 为键、T 为值的对象类型
  • Exclude<T,U>Extract<T,U>:类型差集、交集
  • NonNullable<T>:排除 null、undefined

示例:

typescript 复制代码
interface User {
  id: number;
  name: string;
  age?: number;
}

type PartialUser = Partial<User>; // 所有属性可选
// { id?: number; name?: string; age?: number; }

type RequiredUser = Required<User>; // 所有属性必填
// { id: number; name: string; age: number; }

type ReadonlyUser = Readonly<User>; // 所有属性只读
// { readonly id: number; readonly name: string; readonly age?: number; }

type UserIdAndName = Pick<User, 'id' | 'name'>; // 只保留 id 和 name
// { id: number; name: string; }

type UserWithoutAge = Omit<User, 'age'>; // 去掉 age 属性
// { id: number; name: string; }

type UserMap = Record<string, User>; // 以字符串为 key 的 User 对象集合

四、应用进阶

11. 字符串字面量类型与模板字面量类型

概念说明:

允许"类型"层面限制/组合字符串,强化类型表达能力。

示例:

typescript 复制代码
type Direction = 'up' | 'down' | 'left' | 'right';
type Size = 'small' | 'medium' | 'large';
// 模板字面量类型
type EventName = `on${Capitalize<string>}`;

12. 可辨识联合与索引类型

可辨识联合

通过共同的字面量字段做类型分支判定。

示例:

typescript 复制代码
type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number };

function area(shape: Shape): number {
  if (shape.kind === 'circle') {
    return Math.PI * shape.radius ** 2;
  }
  return shape.side ** 2;
}

索引类型

利用 keyof 提取类型的 key 集合,T[K] 访问属性类型。

示例:

typescript 复制代码
type Point = { x: number; y: number };
type PointKeys = keyof Point; // "x" | "y"
type XType = Point['x']; // number

13. this 类型与流式接口

解释:

在方法内部返回 this,可以实现链式调用风格。

示例:

typescript 复制代码
class Counter {
  count = 0;
  increment(): this {
    this.count++;
    return this;
  }
}
const c = new Counter();
c.increment().increment();

14. 可选链与空值合并运算符

概念说明:

  • ?. 可安全访问嵌套属性
  • ?? 可提供默认值

示例:

typescript 复制代码
const obj = { foo: { bar: 42 } };
const val = obj.foo?.bar; // 42
const def = obj.baz?.qux ?? 'default'; // "default"

五、总结学习建议

TypeScript 类型系统强大且灵活,涵盖如联合、交叉、映射、条件、工具类型等多样特性。熟练掌握这些基础与高阶用法,将显著提升代码的类型安全、复用性与开发效率。日常建议通过不断实践、灵活组合使用类型能力,逐步突破更复杂的类型场景。

相关推荐
90后的晨仔1 天前
5分钟搭建你的第一个TypeScript项目
前端·typescript
路光.1 天前
React中Suspense的分包实践
前端·react.js·typescript
熊猫钓鱼>_>2 天前
仓颉语言:智能应用开发的新范式
ai·typescript·多模态·仓颉·cangjie·智能推荐系统·强类型
时间的情敌2 天前
基于 Vue3 及TypeScript 项目后的总结
前端·vue.js·typescript
Dragon Wu3 天前
Taro 自定义tab栏和自定义导航栏
前端·javascript·小程序·typescript·前端框架·taro
武清伯MVP3 天前
阮一峰《TypeScript 教程》学习笔记——类型映射
笔记·学习·typescript
Pu_Nine_93 天前
Vue 3 + TypeScript 项目性能优化全链路实战:从 2.1MB 到 130KB 的蜕变
前端·vue.js·性能优化·typescript·1024程序员节
快起来别睡了3 天前
TypeScript装饰器详解:像搭积木一样给代码加功能
前端·typescript
嗷呜~3 天前
error 找不到模块“../views/Login.vue”或其相应的类型声明
typescript·vue3