const obj = { wheels: 4, lights: 2, doors: 4 }
someMapFunction(obj, {
props: ["wheel", "lights"],
format: (wheels, lights) => `${wheels}-${lights}` // "4-2"
})
我如何键入someMapFunction
,以便类型记录知道props
只能是obj
的键,format
函数将接受props
数组值在obj
中指向的所有值
发布于 2022-10-09 21:31:50
您可以这样定义函数:
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
的参数类型时,我们使用多元元组语法[...K]
将K
推断为元组,而不是和数组,因为顺序很重要。
对于format
,我们将其声明为一个https://www.typescriptlang.org/docs/handbook/2/functions.html#rest-parameters,其中元素的顺序和类型由一个元组描述。要创建这个元组,我们可以映射元组K
中的元素K
,并使用它们提取相应的T
类型。
https://stackoverflow.com/questions/74010494
复制相似问题