打字稿中是否有一种很好的方式来键入将递归访问对象属性的函数?这是深入两个层次的手动编码示例:
function deepProp<T, K extends keyof T>(obj: T, prop1: K, prop2: keyof T[K]) {
return obj[prop1][prop2];
}
// Example use
const obj = {
user: {
pets: [{
toys: [{
name: "Toughy",
price: 1999
}]
}]
}
} as const
deepProp(obj, "user", "pets");
但是我正在寻找一种好的方法,以使props
函数中的任意数量的deepProp
尽可能地深入。我认为该函数的签名类似于function deepProp(obj, ...props) { }
。有什么好方法吗?谢谢!
答案 0 :(得分:2)
不可能使用任意数量的键,但是您可以根据需要制作类似于lodash's get
的键。
还可以以某种递归方式使用该功能。
上面提到的_.get
(其类型最多支持4个键)的示例:
const obj = {
user: {
pets: [{
toys: [{
name: "Toughy",
price: 1999
}]
}]
}
} as const
const toy1 = _.get(obj, ["user", "pets", 0, "toys"]); // correct type
const toy2 = _.get(obj, ["user", "pets", 0, "toys", 0]); // any :(
const toy3 = _.get(_.get(obj, ["user", "pets", 0, "toys"]), [0]); // correct type :)