Typescript类型体操 - 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'}

English

Give an array, transform into an object type and the key/value must in the given array.

For example:

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'}

答案

type TupleToObject<T extends (string | number)[]> = { [P in T[number]]: P };

在线演示

posted @ 2022-09-02 23:13  Laggage  阅读(118)  评论(0编辑  收藏  举报