Typescript 如何从给定路径创建对象?
类似于Typescript 如何从给定路径创建对象?,typescript,Typescript,类似于。.set我想从给定的路径创建对象 例如: type Path = readonly ['a', 'b']; type Object = SOMETHING<Path, {c: "foo"}>; // {a: {b: {c: "foo" } } } type Path=readonly['a','b']; 类型Object=SOMETHING;//{a:{b:{c:“foo”}} 您知道如何获得这种行为吗?您可以使用遍历路径元组的递归
。.set
我想从给定的路径创建对象
例如:
type Path = readonly ['a', 'b'];
type Object = SOMETHING<Path, {c: "foo"}>; // {a: {b: {c: "foo" } } }
type Path=readonly['a','b'];
类型Object=SOMETHING;//{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" } } }
type KeyPath=readonly PropertyKey[]
键入某物=
P扩展只读[推断键,…推断Rest]
? {[K在摘录中]:某物}
:T
类型Path=readonly['a','b'];
键入Obj=SOMETHING;//{a:{b:{c:“foo”}}
Extract
应用程序是必需的,因为推断的参数不会自动具有正确的约束。如果从SOMETHING
中删除扩展键路径
,则可以删除提取
,但会删除路径参数上的元组检查
谢谢,我还有一个问题,也许你知道答案?