[英]How to convert a union of tuples to an object type
我有一個InputData
類型,它是string
或元組。 我想將其轉換為 object。
type InputType = File | string | boolean;
type InputData = string | [string, InputType]
type test = "username" | "password" | ["isAbove18", boolean] | ["photo", File];
在上面的類型中,只有string
(給出輸入字段的名稱),它的類型應該設置為string
。 我有通用類型
type AddDefaultValues<Data extends InputData> = Data extends string ? [Data, string] : Data
//AddDefaultValues<test> = ["username", string]| ["password", string] | ["isAbove18", boolean] | ["photo", File]
現在我的要求是上面的 map 到下面的 object 。
{username: string, password: string, isAbove18: boolean, photo: File}
我嘗試了很長時間,但無法做出任何事情。 請幫我解決這個問題...
您可以使用帶有鍵重命名的 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;
};
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.