06 泛型函数开发基本类型工具函数

104 阅读2分钟

初篇

熟悉泛型函数的基本使用了吗?

是的

TypeScript操作类型的语法有哪一些吗?

keyof typeof extends 操作符
工具泛型函数类型 Uppercase Pick 等

好的开始进阶吧

进阶

Keyof Type Operator基本用法是什么 ?

提取对象类型的键值

type TwoD = {x: number, y: number}
type XorY = keyof TwoD

const keyX: XorY = 'x'

interface ThreeD {
  x: number,
  y: number,
  z: number
}

type ThreeDKey = keyof ThreeD

type ArrStr = { [k: string]: string }

type StrOrNum = keyof ArrStr

什么是Mapped Types吗?

规定对象键值的类型

type MapType = {
  [key: string]: string | boolean
}

type MapGeneric<NeedType> = {
  [key: string]: NeedType
}

const OnlyStrAndBol: MapGeneric<string | boolean> = {
  name: 'jack',
  young: true,
  age: 11 // Error
}

Typeof Type Operator基本用法是什么 ?

用来提取表达式的类型

用在表达式中

   var x = 5;
   // 用在表达式中,返回 ‘number’ 字符串,即JS中的用法
   var y = typeof x; // Use in an expression

用在类型提取中,即TS拓展的类型语法

   var x = 5;
   // 用在类型提取中,即TS拓展的类型语法
   var z: typeof x; // Use in a type query

Typeof Type Operator提取本身会怎样?

会返回any类型

let c: typeof c

递归类型是怎样产生的?

对象键值引用本省产生递归类型
函数返回本身产生递归类型

   // 递归类型

   var d: { a: typeof d}

   var h: () => typeof h;

typeof的类型守卫是什么?

指通过typeof操作符缩窄类型到具体的类型

function numOrStr(param: number | string) {
  if(typeof param === 'number') {
    return param.toFixed(1)
  } else {
    return param.length // 缩窄类型到 string
  }
}

function isLongStr(param: any) {
  return typeof param === 'string' && str.length > 100
}

Partial的基本应用以及其泛型函数的实现?

将对象类型键值全部转化为可选类型

  type P =  {
    x: number,
    y: string
  }

  type P2 = Partial<P>

  type PGeneric<Type> = {
    [Key in keyof Type]?: Type[Key]
  }

  type P3 = PGeneric<P>

Required?

将对象类型键值全部转化为必填类型

泛型定义关键点 ** -?**语法

  type P =  {
    x: number,
    y: string
  }

  type Req = Required<P>

  let a: P = {
    x: 1
  }
  // 编译报错
  let b: Req = {
    x: 1
  }
  
  
 type ReqGeneric<Parameter> = {
    [Key in keyof Parameter]-?: Parameter[Key]
  }

  type Req2 = ReqGeneric<P>



Record<UnionType, ObjType>怎样实现?

关键点泛型实现 需要限制第一个参数是符合对象键的规范即只能是 string | number | symbol
**Keys extends string | number | symbol**

// 基本使用
interface CatInfo {
    age: number;
    breed: string;
  }

type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

cats.bulb; // 报错
// 泛型实现  需要限制第一个参数是 union type 
type RecGeneric<Keys extends string | number | symbol, TypeObj> = {
  [Key in Keys]: TypeObj;
};

interface PersonInfo {
  age: number;
}

type PersonName = "jack" | "molly";
const key = '1' as '1'
const persons: RecGeneric<PersonName, PersonInfo> = {
  jack: { age: 1 },
  molly: { age: 2 },
};