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

时间:2019-04-17 13:01:28

标签: 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)

我希望它的工作原理与第一个示例相同。

I've created a CodeSandbox example here

(单击链接后单击在编辑器中打开以查看错误)

0 个答案:

没有答案