1. 泛型定义函数:
function identity<T>(arg: T): T {
  return arg;
}

该函数定义了一个泛型类型T,可以接受任意类型的参数,并返回相同类型的结果。例如:

let result1 = identity<string>("hello");
let result2 = identity<number>(123);
  1. 泛型定义类:
class GenericNumber<T> {
  zeroValue: T;
  add: (x: T, y: T) => T;
}

该类定义了一个泛型类型T,包含一个属性和一个方法。属性zeroValue的类型为T,方法add接受两个参数x和y,类型均为T,返回值类型也为T。例如:

let myNumber = new GenericNumber<number>();
myNumber.zeroValue = 0;
myNumber.add = function(x, y) { return x + y; };
  1. 泛型定义接口:
interface GenericIdentityFn<T> {
  (arg: T): T;
}

该接口定义了一个泛型类型T,包含一个函数类型,函数接受一个参数arg,类型为T,返回值类型也为T。例如:

let identityFn: GenericIdentityFn<number> = function(arg) {
  return arg;
};
分别举例描述ts泛型定义函数、类、接口

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

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