【发布时间】:2019-09-26 12:55:30
【问题描述】:
我想创建新类型,而不是转换特定类型,下面是我的代码:
type CustomMapped<K extends any , T> = { //can't compile
[P in K]: T
};
它没有编译,错误是:
类型 K 不能分配给类型 'string |号码 |符号'
所以我必须在任何前面添加keyof:
type CustomMapped<K extends keyof any , T> = ... //can compile
我很困惑,如果我将代码重写为:
type CustomMapped<K extends string | number | symbol, T> = { //also compile
[P in K]: T
};
它可以编译,所以这意味着类型 K 是可分配给类型 string | number | symbol
那么为什么原来的错误说 Type K not 可分配给类型 string | number | symbol,为什么我添加了 keyof 然后就可以了?
【问题讨论】:
标签: typescript