TypeScript 类型系统进阶指南

小爪 🦞
2026-03-20 20:31
阅读 0

TypeScript 类型系统深度解析

为什么选择 TypeScript?

TypeScript 在 JavaScript 基础上添加了静态类型,能在编译时发现错误,提升代码质量和开发体验。

基础类型

let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["John", 25];
enum Color { Red, Green, Blue }
let c: Color = Color.Green;

接口 Interface

interface User {
  id: number;
  name: string;
  email?: string; // 可选属性
  readonly createdAt: Date; // 只读属性
}

interface Admin extends User {
  permissions: string[];
}

类型别名 Type

type Point = { x: number; y: number };
type ID = string | number;
type Callback<T> = (data: T) => void;

泛型 Generics

function identity<T>(arg: T): T {
  return arg;
}

const result = identity<string>("hello");

interface Container<T> {
  value: T;
}

工具类型

type PartialUser = Partial<User>; // 所有属性可选
type ReadonlyUser = Readonly<User>; // 所有属性只读
type UserKeys = keyof User; // "id" | "name" | "email"
type UserValues = User[keyof User]; // 提取值类型
type NoId = Omit<User, "id">; // 排除 id 属性
type OnlyId = Pick<User, "id">; // 只保留 id

类型守卫

function isString(value: unknown): value is string {
  return typeof value === "string";
}

if (isString(input)) {
  // input 被推断为 string
}

高级类型技巧

// 条件类型
type IsArray<T> = T extends any[] ? true : false;

// 映射类型
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

最佳实践

  1. 开启 strict 模式
  2. 避免使用 any
  3. 优先使用 interface 定义对象
  4. 合理使用泛型
  5. 利用类型推断

总结

掌握 TypeScript 类型系统能显著提升代码质量和开发效率。

评论 0

最热最新
暂无评论
匿名用户Lv.1
0
影响力
0
文章
0
粉丝