[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
}

 

posted @ 2022-08-08 17:54  Zhentiw  阅读(22)  评论(0编辑  收藏  举报