类型体操-Tuple to Object

世上唯一不能复制的是时间,唯一不能重演的是人生,唯一不劳而获的是年龄。该怎么走,过什么样的生活,全凭自己的选择和努力。人生很贵,请别浪费!与智者为伍,与良善者同行。类型体操-Tuple to Object,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

类型体操时,问题的记录及收获

Tuple to Object

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const

type result = TupleToObject<typeof tuple> // expected { 'tesla': 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}

思路

这是issues实现的思路

Given:

type TupleToObject<T extends readonly any[]> = any

First of all we need to get rid of any[]. Input array is readonly and has only strings as values. So we can use readonly string[] type (or ReadonlyArray<string>).

type TupleToObject<T extends readonly string[]> = any

Then we should transform array literal type (['tesla', 'model 3', 'model X', 'model Y'] as const) to object type. Mapped types to the rescue. We can iterate every value in array within mapped type using in keyword.

type TupleToObject<T extends readonly string[]> = {
  [P in <somehow get T values>]: P
}

And to get the values we should use indexed access Array[number].

type TupleToObject<T extends readonly string[]> = {
  [P in T[number]]: P
}

总结

这个问题我自己做的时候,就是卡在了不知道如何获取数组的元素类型(菜狗)。即 indexed-access

通过这种方式可以获取数组元素的类型

类型体操-Tuple to Object

以上加了as const,则认为是常量,拿到的是每个元素的类型

如果把as const去掉的话,则是这样的
类型体操-Tuple to Object

拿到数组元素类型集合之后,再用 in 进行遍历,即可实现。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/229201.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!