其他分享
首页 > 其他分享> > [Typescript] Generics constraint

[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,string,constraint,item,dict,Generics,interface,Dict,id
来源: https://www.cnblogs.com/Answer1215/p/16562849.html