typescript 泛型

简单使用

// 泛型 ‘C’可随意取
function id<C>(value: C): C {
  return value;
}
const num = id<number>(3);
let str = id<string>("3"); // <string>可省略

 泛型约束

// 指定具体类型
function id1<C>(value: C[]): C[] {
  console.log(c.length);
  return value;
}
id1([1, 2, 3]);
// 添加约束
interface ILength {
  length: number;
}
function id2<C extends ILength>(value: C): C {
  console.log(c.length);
  return value;
} // 表示传入的值必须具有length属性
id2("qwee");
id2([1, 2, 3]);

 泛型多个类型变量

// keyof接受一个对象类型,生成以键名组成的联合类型,例:'name'|'age'
function getProp<Type, Key extends keyof Type>(obj: Type, key: Key) {
  return obj[key];
}
getProp({ name: "jim" }, "name"); // 'jim'
getProp([1, 2, 3], 1); // 2
getProp("asdf", 2); // d

接口中使用泛型

interface IdFun<Type> {
  id: (value: Type) => Type;
  ids: () => Type[];
}
let IdObj: IdFun<number> = {
  id(value) {
    return value;
  },
  ids() {
    return [123];
  },
};

类中使用泛型

// 方法1
class Example1<Type> {
  defaultValue: Type;
  add: (x: Type, y: Type) => Type;
  constructor(value: Type) {
    this.defaultValue = value;
  }
}
const numa = new Example1(19);
// 方法2
class Example2<Type> {
  defaultValue: Type;
  add: (x: Type, y: Type) => Type;
}
const myNum = new Example2<number>();
myNum.defaultValue = 123;

泛型工具类型

interface Props {
  id: number;
  children: number[];
}
// Partial<Type>,将类型Type的所有属性设置为可选
type PartialProps = Partial<Props>;
let pro: PartialProps = {}; // id、children此时为可选属性

// Readonly<Type>,将类型Type的所有属性设置只读
type ReadonlyProps = Readonly<Props>;
let pro1: ReadonlyProps = { id: 1, children: [1] };
// pro1.id=2 此时会报错

// Pick<Type>,从Type中选择属性来构造新类型
type PicckProps = Pick<Props, "id" | "children">;

// Record<Keys,Type>,Keys:表示对象有哪些属性;Type:表示属性类型
type RecordObj = Record<"a" | "b", string[]>;
let reObj: RecordObj = {
  a: ["1"],
  b: ["2"],
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值