[英]How to convert a union of tuples to an object type
I have a type InputData
which is either string
or a tuple.我有一个
InputData
类型,它是string
或元组。 I want to transform it to object.我想将其转换为 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
.在上面的类型中,只有
string
(给出输入字段的名称),它的类型应该设置为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.现在我的要求是上面的 map 到下面的 object 。
{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:您可以使用带有键重命名的 object 映射:
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;
};
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.