![](/img/trans.png)
[英]How to convert a mapped generic type to an union of tuples in typescript
[英]How to use a generic union type in a mapped type with Typescript?
我想生成具有通用聯合類型的映射類型。
考慮下面的工作示例
type Keys = "container" | "body" | "button"
type Styles = { [K in Keys]: CSSProperties }
這按預期工作。 但是,如果我嘗試讓 Styles 類型采用泛型並做同樣的事情,它就會分崩離析。 例如
type Styles<Keys> = { [K in Keys]: CSSProperties }
const styles: Styles<"container" | "body" | "button"> = {...}
這個錯誤與
(type parameter) Keys in type Styles<Keys>
Type 'Keys' is not assignable to type 'string | number | symbol'.
Type 'Keys' is not assignable to type 'symbol'.ts(2322)
我希望它能像第一個例子一樣工作。
(單擊鏈接后單擊“在編輯器中打開”按鈕以查看錯誤)
我為此創建了映射器,它看起來像這樣:
export type TypesToObjectMapper<Union extends string | number | symbol, T> = {
[Prop in Union]: T;
};
並使用示例:
export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE';
type TestType = TypesToObjectMapper<RequestMethodType, boolean>;
結果:
type SignalRSettings = {
GET: boolean;
POST: boolean;
PUT: boolean;
DELETE: boolean;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.