TypeScript 泛型详解:12 个使用场景及案例

泛型是一种在编译时期不确定类型的特性,可以在代码中定义一种通用的数据类型,以便在不同的场景中使用。泛型可以使代码更具可读性和可重用性,同时还能提高代码的类型安全性。

以下列举了 12 个常见的泛型使用场景,并附带代码示例:

1. 集合类

// 定义一个列表类
class List<T> {
  private items: T[] = [];

  push(item: T) {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }
}

// 实例化一个字符串列表
const strList = new List<string>();
strList.push('hello');
strList.push('world');
console.log(strList.pop()); // 输出: 'world'

// 实例化一个数字列表
const numList = new List<number>();
numList.push(123);
numList.push(456);
console.log(numList.pop()); // 输出: 456

2. 函数式编程

function map<T, U>(array: T[], func: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of array) {
    result.push(func(item));
  }
  return result;
}

const nums = [1, 2, 3, 4, 5];
const square = (x: number) => x * x;
console.log(map(nums, square)); // 输出: [1, 4, 9, 16, 25]

3. 异步编程

async function fetchJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  const data = await response.json();
  return data as T;
}

interface User {
  id: number;
  name: string;
  email: string;
}

const user = await fetchJson<User>('https://jsonplaceholder.typicode.com/users/1');
console.log(user); // 输出: { id: 1, name: 'Leanne Graham', email: 'Sincere@april.biz' }

4. 接口

interface List<T> {
  items: T[];
  push(item: T): void;
  pop(): T | undefined;
}

class ArrayList<T> implements List<T> {
  items: T[] = [];

  push(item: T) {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }
}

const strList: List<string> = new ArrayList<string>();
strList.push('hello');
strList.push('world');
console.log(strList.pop()); // 输出: 'world'

5. 类型别名

type Result<T> = {
  success: boolean;
  data: T;
  error?: string;
};

type UserResult = Result<User>;

const userResult: UserResult = {
  success: true,
  data: {
    id: 1,
    name: 'Leanne Graham',
    email: 'Sincere@april.biz'
  }
};

console.log(userResult); // 输出: { success: true, data: { id: 1, name: 'Leanne Graham', email: 'Sincere@april.biz' } }

6. 函数类型

type MapFunc<T, U> = (array: T[], func: (item: T) => U) => U[];

const map: MapFunc<number, number> = (array, func) => {
  const result: number[] = [];
  for (const item of array) {
    result.push(func(item));
  }
  return result;
}

const nums = [1, 2, 3, 4, 5];
const square = (x: number) => x * x;
console.log(map(nums, square)); // 输出: [1, 4, 9, 16, 25]

7. 类类型

interface List<T> {
  items: T[];
  push(item: T): void;
  pop(): T | undefined;
}

class ArrayList<T> implements List<T> {
  items: T[] = [];

  push(item: T) {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }
}

const strList: List<string> = new ArrayList<string>();
strList.push('hello');
strList.push('world');
console.log(strList.pop()); // 输出: 'world'

8. 类静态属性和方法

class Singleton<T> {
  private static instance: T;

  static getInstance(): T {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton<T>();
    }
    return Singleton.instance;
  }
}

class MyClass {
  private constructor() {}
}

const myClass = Singleton.getInstance<MyClass>();
console.log(myClass); // 输出: MyClass {}

9. 函数返回类型

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

const str = identity<string>('hello');
console.log(str); // 输出: 'hello'

10. 函数参数类型

function map<T, U>(array: T[], func: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of array) {
    result.push(func(item));
  }
  return result;
}

const nums = [1, 2, 3, 4, 5];
const square = (x: number) => x * x;
console.log(map<number, number>(nums, square)); // 输出: [1, 4, 9, 16, 25]

总结

泛型是 TypeScript 中一个强大的特性,它可以帮助我们编写更灵活、更可重用、更安全的代码。希望本文能帮助你更好地理解泛型,并将其应用到你的 TypeScript 项目中。

TypeScript 泛型详解:12 个使用场景及案例

原文地址: https://www.cveoy.top/t/topic/nqFg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录