如何做到这一点的第一个近似值在 Tao 的回答中,问题是如果你添加更多属性,它不会按预期工作:
type Foo = {
outer: {
inner: any;
}
outer2: {
inner2: any;
}
}
type PropertyList<T, K1 extends keyof T = keyof T, K2 extends keyof T[K1] = keyof T[K1]> = [K1, K2];
let myList:PropertyList<Foo> = ["outer", "inner"] // error, since K2 will have to be a property of both outer and outer2
您可以使用函数来帮助根据传递的实际参数推断出正确的类型。我们需要使用两个函数的方法,因为我们需要为 和 提供通用参数,T
但我们只想指定,如果我们指定一个,我们必须指定所有参数:K1
K2
T
function pathFor<T>() {
return function <K1 extends keyof T, K2 extends keyof T[K1]>(outer: K1, inner: K2): [K1,K2]{
return [outer, inner];
}
}
// Usage
let myList = pathFor<Foo>()("outer", "inner"); // typed as ["outer, "inner"]
let myList2 = pathFor<Foo>()("outer2", "inner"); // error, inner is not part of outer2
let myList3 = pathFor<Foo>()("outer2", "inner2"); // typed as ["outer2, "inner2"]
编辑
您还可以扩展该函数以获取有限长度的路径(示例中为 4,但根据需要添加更多):
function keysFor<T>() {
function keys<K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3]>(outer: K1, inner: K2, innerInner: K3, innerInnerInner: K4): [K1,K2, K3, K4]
function keys<K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(outer: K1, inner: K2, innerInner: K3): [K1,K2, K3]
function keys<K1 extends keyof T, K2 extends keyof T[K1]>(outer: K1, inner: K2): [K1,K2]
function keys(): string[]{
return [...arguments];
}
return keys
}