网站搜索

如何在 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)

我希望它的工作方式和第一个例子一样。

我在这里创建了一个 CodeSandbox 示例

(在点击链接后,点击“在编辑器中打开”按钮以查看错误)

答案#1

我已经为此创建了映射器,看起来是这样的:

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