typescript - 如何将对象属性名称数组映射到给定对象中名称所指向的值数组

标签 typescript

const obj = { wheels: 4, lights: 2, doors: 4 }

someMapFunction(obj, { 
  props: ["wheel", "lights"], 
  format: (wheels, lights) => `${wheels}-${lights}` // "4-2"
})

我如何输入 someMapFunction 以便 typescript 知道 props 只能是 obj 的键以及 format 函数将获取 props 数组值在 obj 中指向的所有值?

最佳答案

您可以像这样定义函数:

function someMapFunction<
  T, 
  K extends (keyof T)[]
>(obj: T, propsAndFormat: { 
  props: [...K], 
  format: (...args: {
    [I in keyof K]: T[K[I]]
  }) => string 
}) {
  return null!
}

它有两个通用参数TKT 描述了作为 obj 传递的对象的类型,而 KT 的键元组。当我们声明 props 的参数类型时,我们使用 variadic tuple语法 [...K]K 推断为 元组 而不是 数组,因为顺序很重要.

对于格式,我们将其声明为 rest parameter其中元素的顺序和类型由元组描述。为了创建这个元组,我们可以映射元组K中的元素I,并使用它们来提取T的相应类型。


Playground

关于typescript - 如何将对象属性名称数组映射到给定对象中名称所指向的值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74010494/

相关文章:

javascript - 从 firebase firestore 引用获取异步值

angular - 你如何包含/扩展带有 rollup、typescript、angular 2 的 JS 库

node.js - 无法通过Kubernetes上的Node.Js连接到Elasticsearch(证书链中的自签名证书)

typescript - 导出的变量 X 具有或正在使用来自外部模块 Z 的名称 Y,但无法命名

Angular 2等待同步方法

javascript - Angular 2 中组件特定的 HostListener

typescript - @types - 对象键的值数组

javascript - 单击"is"按钮时添加边框和背景颜色

typescript - 定义没有索引签名的 typescript 对象形状

typescript - 仅用于类型检查的引用 .ts 文件