简体   繁体   English

如何在 Typescript 的映射类型中使用通用联合类型?

[英]How to use a generic union type in a mapped type with Typescript?

I want to generate a mapped type with a generic union type.我想生成具有通用联合类型的映射类型。

Consider the working example below考虑下面的工作示例

type Keys = "container" | "body" | "button"

type Styles = { [K in Keys]: CSSProperties } 

This works as expected.这按预期工作。 But, if I try to make the Styles type take a generic and do the same thing it falls apart.但是,如果我尝试让 Styles 类型采用泛型并做同样的事情,它就会分崩离析。 For example例如

type Styles<Keys> = { [K in Keys]: CSSProperties }

const styles: Styles<"container" | "body" | "button"> = {...}

This errors with这个错误与

(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)

I would expect it to work the same as the very first example.我希望它能像第一个例子一样工作。

I've created a CodeSandbox example here我在这里创建了一个 CodeSandbox 示例

(Click the open in editor button after following the link to see the errors) (单击链接后单击“在编辑器中打开”按钮以查看错误)

I have created mapper for that and it looks like that:我为此创建了映射器,它看起来像这样:

export type TypesToObjectMapper<Union extends string | number | symbol, T> = {
    [Prop in Union]: T;
};

And use exaple:并使用示例:

export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE';
type TestType = TypesToObjectMapper<RequestMethodType, boolean>;

Result:结果:

type SignalRSettings = {
    GET: boolean;
    POST: boolean;
    PUT: boolean;
    DELETE: boolean;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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