相关疑难解决方法(0)

对象属性路径的 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
Run Code Online (Sandbox Code Playgroud)

链接到 TypeScript 游乐场

reflection recursion types typescript jsonpointer

11
推荐指数
1
解决办法
2万
查看次数

标签 统计

jsonpointer ×1

recursion ×1

reflection ×1

types ×1

typescript ×1