typescript - 如何表达 "K extends keyof T such that T[K] is of type V"?

标签 typescript

我想创建一个像这样的函数签名:

countBy<R, V>(objs: R[], iteratee: ((x: R) => V) | keyof R): Map<V, number> {}

在 lodash 风格中,iteratee 应该是函数 (x: R) => V 或简写 R 的关键:

countBy(pizzas, pizza => pizza.sauce)
countBy(pizzas, 'sauce')

如何告诉 Typescript,如果我使用简写 ('sauce'),R[keyof R] 必须生成 V< 类型的值

最佳答案

假设您不需要键入函数体(这比较棘手),您可以创建两个重载来实现此目的:

function countBy<R, V>(objs: R[], iteratee: ((x: R) => V)): Map<V, number>
function countBy<R, K extends keyof R, V extends R[K]>(objs: R[], iteratee: K): Map<V, number>
function countBy<R, V>(objs: R[], iteratee: ((x: R) => V) | keyof R): Map<V, number> {
  return {} as any
}

TypeScript playground

关于typescript - 如何表达 "K extends keyof T such that T[K] is of type V"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71533263/

相关文章:

typescript - 有没有Partial的替代方法,它仅接受其他类型的字段,而别无其他?

angular - 如何从 Angular Material 日期选择器更改日期?

javascript - 为什么索引会这样增加? javascript

javascript - 使用 typescript 安装express.js 的正确方法是什么?

node.js - 如何发出将数组发送到服务器的请求?

javascript - Typescript:将字符串作为 HTML 打印到终端?

angular - 将 WebStorm TSLint 错误行更改为警告行

angular - 需要阻止右键单击 PDF Angular 2

javascript - 如何用 Protractor 选择组件元素?

javascript - Angular 4 组件 : call javascript/jquery code from another file