type a = 'one' | 'two'
我想有一个这样的type b
type b = 'ONE' | 'TWO'
所以我尝试了
type a = 'one' | 'two'
type b = {[P in a]: P['toUpperCase']}
但这并没有做我想要它做的事情。
感谢您阅读:)
现在,您可以通过引入模板文本类型来执行此操作:
type A = 'one' | 'two'
type B = Uppercase<A>
let b: B = 'one' // Type '"one"' is not assignable to type '"ONE" | "TWO"'.
TS游乐场
除了Uppercase<StringType>
之外,还有以下帮助程序类型:
- 小写
- 利用
- 取消资本化
它们可以在模板文本类型中使用,如下所示:
type Fruit = 'Apple' | 'Banana'
type FruitField = `fr_${Uncapitalize<Fruit>}`
const fruit: Record<FruitField, boolean> = {
'fr_apple': true,
'fr_banana': false,
'fr_Apple': true, // error
'fr_peach': false // error
}
TS游乐场
这里有TS Playground的链接
这是代码:
type A = 'one' | 'two'
type B = Uppercase<A>
let b: B = 'one' // Error
附言我不明白为什么在上一条评论中使用了更复杂的形式来写同样的东西
编辑: Derek Nguyen(最佳答案(现在用更新、更简单的解决方案改变了他的答案。