具有约束条件的泛型的打字稿类型注释

时间:2020-07-17 12:24:32

标签: typescript generics

我有一个泛型的咖喱函数,我不知道如何使用它而不会丢失精确的类型信息。我可以通过指定一个具体的类型来使用它,但是我不能在另一个上下文中使用它。我可以使用最少的类型,但是打字稿会丢失有关函数输出的信息。

/* eslint-disable @typescript-eslint/no-unused-vars */
const filterBy = <T>(check: (x: T) => boolean) => (arr: T[]): T[] => {
  return arr.filter(check)
}

interface SpecializedTypeWithIdAndMore {
  id: string
  anotherField: string
}

const items: SpecializedTypeWithIdAndMore[] = [
  /* ... */
]

// This is working but can only be applied to SpecializedTypeWithIdAndMore
const grouperSpecialized = filterBy<SpecializedTypeWithIdAndMore>(
  x => x.id === 'something',
)
const groupedItemsSpecialized = grouperSpecialized(items)
// groupedItemsSpecialized is SpecializedTypeWithIdAndMore[]

// This is working, but information about the input type is lost
const grouperTypeLost = filterBy<{ id: string }>(x => x.id === 'something')
const groupedItemsTypeLost = grouperTypeLost(items)
// groupedItemsTypeLost is { id: string }[]

// I would like to write something like this, but it does not work
const grouperWanted = filterBy<T extends { id: string }>(x => x.id === 'something')
const groupedItemsWanted = grouperWanted(items)
// I would like groupedItemsWanted to be SpecializedTypeWithIdAndMore[]

1 个答案:

答案 0 :(得分:1)

这似乎有效const grouperWanted: <T extends { id: string }>(arr: T[]) => T[] = filterBy(x => x.id === 'something')