Skip to content

05-ts中泛型的简单使用 ​

以上一章节中的SimpleStringStore4 函数为例, 在该函数的入参中我们固定了入参的类型, 加入现在需要支持另一种入参类型, 肯定不能再去重写一个类似的函数来实现. 基于此, 泛型便出现了. 泛型可以理解为将入参的类型再抽象一下, 类似于unknown, 使用的时候是哪种类型, 函数体里面就是哪种类型.

1. 改造上一章的SimpleStringStore4函数 ​

typescript
function SimpleStringStore<T>(initValue: T): [get: () => T, set: (v: T) => void ] {
  let str: T = initValue
  return [
    () => str,
    (v) => {
      str = v
    }
  ]
}

const [get1, set1] = SimpleStringStore<number>(10)
console.log(get1())
set1(100)
console.log(get1())

// 因为初始化的时候设置为null, 所以如果泛型不加string的可选项, 后续set新值就只能为null了
const [get2, set2] = SimpleStringStore<string | null>(null)
console.log(get2())
set2('this is not null')
console.log(get2())

2. 另一个demo(根据对象的某个属性对该对象进行排序) ​

typescript
function rankItem<T>(target: T[], rank: (v: T) => number): T[] {
  const temp = target.map(item => {
    return {
      item,
      rank: rank(item)
    }
  })

  temp.sort((a,b) => a.rank - b.rank)
  return temp.map(rankedItem => rankedItem.item)
}

interface Cat {
  name: string
  hp: number
}

const cats = [
  {
    name: 'lucy',
    hp: 80
  },
  {
    name: 'jack',
    hp: 10
  }
]

console.log('init cats', cats)
const rankedCats = rankItem<Cat>(cats, ({hp}) => hp)
console.log('ranked cats', rankedCats)