gpt4 book ai didi

typescript - 如何从给定的路径创建对象?

转载 作者:行者123 更新时间:2023-12-04 07:43:06 26 4
gpt4 key购买 nike

类似于 _.set我想从给定的 Path 创建对象.
例如:

type Path = readonly ['a', 'b'];
type Object = SOMETHING<Path, {c: "foo"}>; // {a: {b: {c: "foo" } } }
任何想法如何获得这种行为?

最佳答案

您可以使用遍历路径元组的递归条件类型来执行此操作:

type KeyPath = readonly PropertyKey[]
type SOMETHING<P extends KeyPath, T> =
P extends readonly [infer Key, ...infer Rest]
? {[K in Extract<Key, PropertyKey>]: SOMETHING<Extract<Rest, KeyPath>,T>}
: T

type Path = readonly ['a', 'b'];
type Obj = SOMETHING<Path, {c: "foo"}>; // {a: {b: {c: "foo" } } }
Extract应用程序是必要的,因为推断的参数不会自动具有正确的约束。 Extract<Rest, KeyPath>如果 extends KeyPath 可以删除从 SOMETHING 掉线,但会删除对路径参数的元组检查。
TypeScript playground

关于typescript - 如何从给定的路径创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67349764/

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