【发布时间】:2020-04-14 18:19:31
【问题描述】:
是否可以键入字符串数组,使该数组只能是给定对象中的有效属性路径?类型定义应该适用于所有深度嵌套的对象。
例子:
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
【问题讨论】:
-
我不太明白“应该适用于所有深层嵌套的对象。”,因为这似乎是不可能的。但是,您可以输入:
type PropertyPath<Type extends object> = (keyof Type)[];
标签: typescript recursion reflection types jsonpointer