[Typescript] Generics constraint

2022/8/8 23:24:29

本文主要是介绍[Typescript] Generics constraint,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Assume we have the following code:

interface HasId {
  id: string
}
interface Dict<T> {
  [k: string]: T
}
 
function listToDict<T>(list: T[]): Dict<T> {
  const dict: Dict<T> = {}
 
  list.forEach((item) => {
    // Property 'id' does not exist on type 'T'.
    dict[item.id] = item
  })
 
  return dict
}

 

We want to have restraint that, each T should contians `id`:

interface HasId {
  id: string
}
interface Dict<T> {
  [k: string]: T
}

// T extends HasId
function listToDict<T extends HasId>(list: T[]): Dict<T> {
  const dict: Dict<T> = {}

  list.forEach((item) => {
    dict[item.id] = item
  })

  return dict
}

 



这篇关于[Typescript] Generics constraint的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程