![](/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.