JavaScript
x
2
1
type a = 'one' | 'two'
2
I would like to have a type b
like
JavaScript
1
2
1
type b = 'ONE' | 'TWO'
2
So I tried
JavaScript
1
3
1
type a = 'one' | 'two'
2
type b = {[P in a]: P['toUpperCase']}
3
But that does not do what I want it to do.
Thank you for reading 🙂
Advertisement
Answer
You can now do this with the introduction of Template Literal Types:
JavaScript
1
5
1
type A = 'one' | 'two'
2
type B = Uppercase<A>
3
4
let b: B = 'one' // Type '"one"' is not assignable to type '"ONE" | "TWO"'.
5
In addition to Uppercase<StringType>
, there are also the following helper types:
- Lowercase
- Capitalize
- Uncapitalize
They can be used within a Template Literal Types, like below:
JavaScript
1
10
10
1
type Fruit = 'Apple' | 'Banana'
2
type FruitField = `fr_${Uncapitalize<Fruit>}`
3
4
const fruit: Record<FruitField, boolean> = {
5
'fr_apple': true,
6
'fr_banana': false,
7
'fr_Apple': true, // error
8
'fr_peach': false // error
9
}
10