简体   繁体   中英

How to convert a union of tuples to an object type

I have a type InputData which is either string or a tuple. I want to transform it to object.

type InputType = File | string | boolean;
type InputData = string | [string, InputType]

type test = "username" | "password" | ["isAbove18", boolean] | ["photo", File];

In above type where only string (the name of the input field is given) its type should be set to string . I have generic type for that

type AddDefaultValues<Data extends InputData> = Data extends string ? [Data, string] : Data 
//AddDefaultValues<test> = ["username", string]| ["password", string] | ["isAbove18", boolean] | ["photo", File]

Now my requirement is to map above type to an object like below.

{username: string, password: string, isAbove18: boolean, photo: File}

I am trying from a long time but can't make out anything. Kindly help me out with this...

You can use an object mapping with key renaming:

type test = "username" | "password" | ["isAbove18", boolean] | ["photo", File];

type ObjMap = {
  [K in test as K extends [infer F, infer _] ? F : K]: K extends [infer _, infer S] ? S : string;
};

Playground link

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM