TypeScript generic All In One


TypeScript generic All In One

function generic

// arrow function :
// : (name: T) => T 类型定义
// = (name: T) => {} 函数定义
const ArrowFunc: (name: T) => T = (name: T) => {
  return name;
}

// 简写 arrow function =
const ArrowFunc1 = (name: T) => {
  return name;
}

// const sum = (a: T, b: T): any => {
//   return `a = ${a}, b = ${b}`;
// }

// 单个泛型参数 T
const sum = (a: T, b: T) => {
  return `a = ${a}, b = ${b}`;
}

// 类型推断
sum(1, 2);
sum('1', '2');

sum(1, 2);
sum('1', '2');

// 多个泛型参数
const multiGeneric = (a: T, b: P) => {
  return `a = ${a}, b = ${b}`;
}

// 类型推断
multiGeneric(1, 2);
multiGeneric('1', 2);
multiGeneric('1', '2');

multiGeneric(1, 2);
multiGeneric('1', 2);
multiGeneric('1', '2');

class generic


class ArrayData{
  constructor(private arr: T[]) {
    //
  }
  getItem: (index: number) => T = (index: number) => {
    return this.arr[index];
  }
}

const numArr = new ArrayData([1, 2, 3]);
numArr.getItem(1);

const strArr = new ArrayData(['a', 'b', 'c']);
strArr.getItem(1);


type ObjType = {
  name: string;
};

class ArrayDataObj{
  constructor(private arr: T[]) {
    //
  }
  getItem(index: number): T {
    return this.arr[index];
  }
  getItemName(obj: ObjType): string {
    return obj.name;
  }
}

// 没有类型限制 T 可以是任何类型
const objs = new ArrayDataObj([
  {
    name: 'abc',
  },
  {
    name: 'xyz',
    // name: 123,
  }
]);
objs.getItem(1);


// 类型限制 extends, T 只能是限制的指定类型
type LimitTypes = (string | number);

class ArrayData1{
  constructor(private arr: T[]) {
    //
  }
  getItem(index: number): T {
    return this.arr[index];
  }
}

const arr1 = new ArrayData1([1, 2, 3]);
arr1.getItem(1);

// 有类型限制, T 只能是限制的指定类型
const objs1 = new ArrayData1([
  {
    name: 'abc',
  },
]);
objs1.getItem(1);
// Type 'ObjType' does not satisfy the constraint 'LimitTypes'.ts(2344)


demo


refs

https://www.typescriptlang.org/docs/handbook/generics.html

https://www.typescriptlang.org/docs/handbook/2/generics.html

https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#generics


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!