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-10 05: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
复制相似问题