我正在try 围绕react-hook-form
的register
创建包装函数.我无法从包装器函数将兼容类型传递给register
.这个问题并不是专门针对react-hook-form的,而是如何强制执行内部功能参数.
我有示例代码:
interface Child1 {
p1: string;
}
interface Child2 {
p2: number
}
interface Parent {
child1: Child1;
child2: Child2
}
function register(o: "child1.p1" | "child2.p2") {return {}}
function getChildRegister(parent: Parent, parentKey: keyof Parent) {
return function(childKey: keyof Parent[typeof parentKey]) {
return register(`${parentKey}.${childKey}`)
}
}
const p: Parent = {child1: {p1: ""}, child2: {p2: 1}}
const result = getChildRegister(p, "child1")("p1") // error! inner function param is not inferred for some reason
我将child1
传递到getChildRegister
,并期望内部函数参数接受Child1
个键(本例中为p1
个).但由于某种原因,Typescript 只接受string
.如何让内部函数接受子类型键?
提前感谢!