zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Generics constraint

typescript constraint generics
2023-09-14 09:00:45 时间

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
}