TypeScript:元组类型到对象类型

编程入门 行业动态 更新时间:2024-10-27 02:18:47
本文介绍了TypeScript:元组类型到对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑这样的元组:

type MyTuple = [A, B];

其中A 和B 都有一个名为key 的属性.例如,

where A and B both have an attribute named key. For instance,

interface A = { key: 'sandwiches' } interface B = { key: 'pasta' }

我想要以下界面:

interface Result { sandwiches: A; pasta: B; }

有没有办法动态地做到这一点?

Is there a way to do this dynamically?

我在想,如果这是可以实现的,它可能看起来像:

I'm thinking that, if this is achievable, it might look something like:

type MapTuple<T> = { [K in keyof T]: T[K]["key"] }

但这不起作用.

这个问题是 Typescript 的逆:对象类型到数组类型(元组)

This question is the inverse of Typescript: object type to array type (tuple)

推荐答案

这将产生预期的效果.您需要映射元组的所有键属性并为每个键提取元组成员:

This will produce the desired effect. You need to map over all the key properties of the tuple and extract the tuple member for each key :

type MyTuple = [A, B]; interface A { key: 'sandwiches' } interface B { key: 'pasta' } type MapTuple<T extends Array<{ key: string }>> = { [K in T[number]['key']]: Extract<T[number], { key : K}> } type R = MapTuple<MyTuple>

更多推荐

TypeScript:元组类型到对象类型

本文发布于:2023-05-29 23:13:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355160.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   对象   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!