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



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

例:

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

链接到 TypeScript playground

在重复问题的答案中,您可以使用递归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!
//               ~~~~~~~~~~~~~

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

链接到代码

可以使用箭头函数

const object1 = {
someProperty: true
};
const object2 = {
nestedObject: object1,
anotherProperty: 2
};
type PropertyPath<Type extends object> = (x: Type) => any;
let propertyPath1: PropertyPath<typeof object1>;
propertyPath1 = (x) => x.someProperty; // works
propertyPath1 = (x) => x.doesntExist; // should not work
let propertyPath2: PropertyPath<typeof object2>;
propertyPath2 = (x) => x.nestedObject.someProperty; // works
propertyPath2 = (x) => x.nestedObject.doesntExist; // should not work
propertyPath2 = (x) => x.doesntExist; // should not work

游乐场链接

最新更新