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

标签 typescript recursion reflection types jsonpointer

这个问题在这里已经有了答案:





Typescript: deep keyof of a nested object

(5 个回答)


1年前关闭。




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

例子:

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

Link to TypeScript playground

最佳答案

the answer to the question this duplicates您可以使用递归 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"]

我假设它是 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!
//               ~~~~~~~~~~~~~

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

Link to code

关于对象属性路径的 TypeScript 类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59455679/

相关文章:

c - 如何在c中递归地将字符串反转为空字符串

java, 反射, 内部类,

javascript - TypeScript 和文件上传类型

javascript - 关于 javascript 和 BST 递归的初学者问题

javascript - Typescript/Javascript : mailto with subject, 正文和链接数组

recursion - Mathematica中的动态编程: how to automatically localize and/or clear memoized function's definitions

c# - Assembly.CreateInstance 和 Activator.CreateInstance 之间的区别?

c# - 获取基本类型的所有最后后代?

node.js - 在 mongoose .d.ts 中分配自定义方法,这样我就可以在 typescript 中使用 mongoose 的任何地方使用它们

javascript - IHttpPromise 使用 TypeScript 2.5 错误地扩展了 IPromise