698 TypeScript泛型的使用:泛型实现类型参数化,泛型接口,泛型类,泛型约束

认识泛型


泛型实现类型参数化


泛型的基本补充


泛型接口

【通过泛型的方式,实现接口的编写。】


泛型类

【通过泛型的方式,实现类的编写。】


泛型约束


01_认识泛型.ts

// 类型的参数化 【将类型进行参数化,让外界调用的时候,决定使用什么样的类型。】

// 在定义这个函数时, 不决定这些参数的类型
// 而是让调用者以参数的形式告知, 这里的函数参数应该是什么类型
// 【把类型提取到前面进行参数化。】
function sum<Type>(num: Type): Type {
  return num
}

// 1.调用方式一: 明确的传入类型
sum<number>(20)
sum<{ name: string }>({ name: 'why' })
sum<any[]>(['abc'])

// 2.调用方式二: 类型推导
sum(50)
sum('abc')

02_泛型接受类型参数.ts

function foo<T, E, O>(arg1: T, arg2: E, arg3?: O, ...args: T[]) {}

foo<number, string, boolean>(10, 'abc', true)

03_泛型接口的使用.ts

// 【指定泛型的默认类型。】
interface IPerson<T1 = string, T2 = number> {
  name: T1
  age: T2
}

const p: IPerson = {
  name: 'why',
  age: 18,
}

// 我写的
interface IPerson2<T1, T2> {
  name: T1
  age: T2
}

const p2: IPerson2<string, number> = {
  name: 'haha',
  age: 111,
}

console.log(p2)

export {}

04_泛型类的使用.ts

class Point<T> {
  // 【T后面不能加逗号。】
  x: T
  y: T
  z: T

  constructor(x: T, y: T, z: T) {
    this.x = x
    this.y = y
    this.z = z
  }
}

const p1 = new Point('1.33.2', '2.22.3', '4.22.1')
const p2 = new Point<string>('1.33.2', '2.22.3', '4.22.1')
const p3: Point<string> = new Point('1.33.2', '2.22.3', '4.22.1')

const names1: string[] = ['abc', 'cba', 'nba']
const names2: Array<string> = ['abc', 'cba', 'nba'] // 不推荐(react jsx <>)

// 我写的
class Point2<T1, T2, T3> {
  x: T1
  y: T2
  z?: T3

  constructor(x: T1, y: T2, z?: T3) {
    this.x = x
    this.y = y
    this.z = z
  }
}

const p6 = new Point2<string, number, boolean>('aaa', 111, false)
console.log(p6.x, p6.y, p6.z)

// 我写的
class Point3<N, S> {
  x: N
  s: S

  constructor(x: N, s: S) {
    this.x = x
    this.s = s
  }
}

class P extends Point3<number, string> {
  b: boolean

  constructor(x: number, s: string, b: boolean) {
    super(x, s)
    this.b = b
  }
}

const p = new P(12, 'abc', true)
console.log(p) // P { x: 12, s: 'abc', b: true }

05_泛型的类型约束.ts

interface ILength {
  length: number
}

// 【1、T一定具有length属性。 2、使用extends做约束,extends表示是某种类型的子类型。】
function getLength<T extends ILength>(arg: T) {
  return arg.length
}

getLength('abc')
getLength(['abc', 'cba'])
getLength({ length: 100 })

原文地址:https://www.cnblogs.com/jianjie/p/15081123.html