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!
}
它有两个通用参数T
和K
。 T
描述了作为 obj
传递的对象的类型,而 K
是 T
的键元组。当我们声明 props
的参数类型时,我们使用 variadic tuple语法 [...K]
将 K
推断为 元组 而不是 数组,因为顺序很重要.
对于格式
,我们将其声明为 rest parameter其中元素的顺序和类型由元组描述。为了创建这个元组,我们可以映射元组K
中的元素I
,并使用它们来提取T
的相应类型。
关于typescript - 如何将对象属性名称数组映射到给定对象中名称所指向的值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74010494/