简体   繁体   中英

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. 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

(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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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