gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:36:52 25 4
gpt4 key购买 nike

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





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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com