typescript 泛型

35 阅读1分钟

TypeScript中的泛型是一种在编写代码时使用类型参数来创建可重用组件的方式。通过使用泛型,您可以编写能够适用于多种类型的函数、类或接口,从而提高代码的灵活性和复用性。

泛型语法:函数名字后面跟一个<参数名> 参数名可以随便写,这里我使用了T

//在不使用泛型时,同样的方法,只是类型不一致 我们就需要写多个方法 这种明显是不友好的
function getValue(a: number, b: number): Array<number> {
  return [a, b];
}
function getValue(a: string, b: string): Array<string> {
  return [a, b];
}
//使用泛型就可以解决这个问题
function getValue<T>(a: T, b: T): Array<T> {
  return [a, b];
}
getValue(1, 2); //function getValue<number>(a: number, b: number): number[]
getValue("1", "2"); //function getValue<string>(a: string, b: string): string[]

//泛型可以有多个 可以添加默认值
function getValue<T = number, K = string>(a: T, b: K): Array<T | K> {
  return [a, b];
}
getValue(); //function getValue<number, string>(a: number, b: string): (string | number)[]
getValue(1, false); //function getValue<number, boolean>(a: number, b: boolean): (number | boolean)[]

//type interface 都可以定义泛型
type A<T> = number | string | T;
let a: A<boolean> = false;

interface B<T> {
  type: T;
}
let b: B<boolean> = {
  type: false,
};


//常用的  模拟了一个接口请求
const axios = {
  get<T>(url: string): Promise<T> {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText));
        }
      };
      xhr.send(null);
    });
  },
};
interface Data {
  message: string;
  code: number;
}
axios.get<Data>("./data.json").then((res) => {
  if (res.code === 200) {
    console.log(res.message);
  }
});

泛型约束:在类型后面跟一个extends再跟一个约束类型

function add<T extends number>(a: T, b: T) {
  return a + b;
}

interface Len {
  length: number;
}
function getLength<T extends Len>(a: T) {
  return a.length;
}

使用 keyof 约束对象:

let obj = {
  name: "张三",
  sex: "男",
};
function ob<T extends object, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}
ob(obj, "name");

interface Data {
  name: string;
  age: number;
  sex: string;
}
type Options<T extends object> = {
  [Key in keyof T]?: T[Key];
};
type A = Options<Data>;