其他分享
首页 > 其他分享> > Typescript类型体操 - Tuple To Object

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

在线演示

标签:Typescript,const,Tuple,tesla,Object,元组,model,type,TupleToObject
来源: https://www.cnblogs.com/laggage/p/16651647.html