type a = 'one' | 'two'
I would like to have a type b like
type b = 'ONE' | 'TWO'
So I tried
type a = 'one' | 'two'
type b = {[P in a]: P['toUpperCase']}
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:
type A = 'one' | 'two' type B = Uppercase<A> let b: B = 'one' // Type '"one"' is not assignable to type '"ONE" | "TWO"'.
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:
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
}