1. 泛型是一种在编译时期不确定类型的特性,可以在代码中定义一种通用的数据类型,以便在不同的场景中使用。

  2. 泛型的使用场景包括但不限于:集合类、函数式编程、异步编程等。

  3. 泛型可以用于定义数组、列表等集合类,如下所示:

// 定义一个列表类
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
  1. 泛型可以用于函数式编程,如下所示:
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]
  1. 泛型可以用于异步编程,如下所示:
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" }
  1. 泛型可以用于定义接口,如下所示:
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
  1. 泛型可以用于定义类型别名,如下所示:
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" } }
  1. 泛型可以用于定义函数类型,如下所示:
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]
  1. 泛型可以用于定义类类型,如下所示:
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
  1. 泛型可以用于定义类的静态属性和方法,如下所示:
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 {}
  1. 泛型可以用于定义函数的返回类型,如下所示:
function identity<T>(value: T): T {
  return value;
}

const str = identity<string>('hello');
console.log(str); // 输出: hello
  1. 泛型可以用于定义函数的参数类型,如下所示:
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 如何对泛型进行理解以及泛型的使用场景列举12个案例说明

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

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