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

Typescript类型体操 - Tuple To Object

时间:2022-09-02 23:22:36浏览次数:95  
标签:Typescript const Tuple tesla Object 元组 model type TupleToObject

题目

中文

传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。

例如:

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
From: https://www.cnblogs.com/laggage/p/16651647.html

相关文章

  • [Typescript Challenges] 10. Medium - Include
    ImplementtheJavaScript Array.includes functioninthetypesystem.Atypetakesthetwoarguments.Theoutputshouldbeaboolean true or false.Forexa......
  • Python源码学习-Objects类型
    目录简介类型定义类型对象对象操作缓存池本文基于Python3.10.4。简介在python中,有两种类型可以保存bytes(字节)类型的数据。分别是bytes与bytearray。其中bytearray支持修......
  • how to use vanilla js iterate the Symbol Object All In One
    howtousevanillajsiteratetheSymbolObjectAllInOnebug❌UncaughtTypeError:UIComponentsisnotiterableimport*asUIComponentsfrom'./index'......
  • [Typescript Challenges] 7. Easy - Awaited
    IfwehaveatypewhichiswrappedtypelikePromise.Howwecangetatypewhichisinsidethewrappedtype?Forexample:ifwehave Promise<ExampleType> ho......
  • [Typescript Challenges] 4. Easy - First of Array
    Implementageneric First<T> thattakesanArray T andreturnsit'sfirstelement'stype.typearr1=['a','b','c']typearr2=[3,2,1]typehead1=F......
  • [Typescript Challenges] 5. Easy - Length of Tuple
    Forgivenatuple,youneedcreateageneric Length,pickthelengthofthetupleForexample:typetesla=['tesla','model3','modelX','modelY']typesp......
  • [Typescript Challenges] 6 Easy - Exclude
    Implementthebuilt-inExclude<T,U>Forexample:typeResult=MyExclude<'a'|'b'|'c','a'>//'b'|'c' /*_____________YourCodeHere_____________......
  • Typescript类型体操 - Readonly 2
    题目中文实现一个通用MyReadonly2<T,K>,它带有两种类型的参数T和K。K指定应设置为Readonly的T的属性集。如果未提供K,则应使所有属性都变为只读,就像普通的Readonly<T>一......
  • Typescript类型体操 - Pick
    题目要求实现TS内置的Pick<T,K>,但不可以使用它。从类型T中选择出属性K,构造成一个新的类型。例如:interfaceTodo{title:stringdescription:stringco......
  • 使用 kubectl patch 修改 Kubernetes objects
    为了能够修改Kubernetes对象,我们可以使用kubectledit以交互方式进行修改。如果我们需要测试值,它可以派上用场,但它使自动化变得更加困难。如果我们需要一种使用非交互式命......