对象属性路径的 TypeScript 类型定义

Joh*_*ald 11 reflection recursion types typescript jsonpointer

是否可以以这样的方式键入字符串数组,使得该数组只能是给定对象中的有效属性路径?类型定义应该适用于所有深度嵌套的对象。

例子:

const object1 = {
    someProperty: true
};
const object2 = {
    nestedObject: object1,
    anotherProperty: 2
};

type PropertyPath<Type extends object> = [keyof Type, ...Array<string>]; // <-- this needs to be improved

// ----------------------------------------------------------------

let propertyPath1: PropertyPath<typeof object1>;

propertyPath1 = ["someProperty"]; // works
propertyPath1 = ["doesntExist"]; // should not work

let propertyPath2: PropertyPath<typeof object2>;

propertyPath2 = ["nestedObject", "someProperty"]; // works
propertyPath2 = ["nestedObject", "doesntExist"]; // should not work
propertyPath2 = ["doesntExist"]; // should not work
Run Code Online (Sandbox Code Playgroud)

链接到 TypeScript 游乐场

jca*_*alz 16

这个重复问题的答案中,您可以使用递归Paths<>Leaves<>类型别名,具体取决于您是否想要支持从根开始并在树中任何位置结束的所有路径 ( Paths<>),或者如果您只想支持以下路径从树的根开始,到叶子结束 ( Leaves<>):

type AllPathsObject2 = Paths<typeof object2>;
// type AllPathsObject2 = ["nestedObject"] | ["nestedObject", "someProperty"] | 
//  ["anotherProperty"]

type LeavesObject2 = Leaves<typeof object2>;
// type LeavesObject2 = ["nestedObject", "someProperty"] | ["anotherProperty"]
Run Code Online (Sandbox Code Playgroud)

我假设是,Paths但您可以将其更改为Leaves适合您的用例。这是您得到的行为,它符合您的要求:

let propertyPath1: Paths<typeof object1>;
propertyPath1 = ["someProperty"]; // works
propertyPath1 = ["doesntExist"]; // error!
//               ~~~~~~~~~~~~~~

let propertyPath2: Paths<typeof object2>;
propertyPath2 = ["nestedObject", "someProperty"]; // works
propertyPath2 = ["nestedObject", "doesntExist"]; // error!
//                               ~~~~~~~~~~~~~
propertyPath2 = ["doesntExist"]; // error!
//               ~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

好的,希望有帮助;祝你好运!

链接到代码