Template Literal Types with Typescript

16 August 2021

Updated: 03 September 2023

Template literal types provide us a way to combine string types or enums in Typescript.

In the below example, we can make use of a string type called Action and an enum called Resource to define a type which is a combination of an action combined with a resource

1
type Action = 'UPDATE' | 'CREATE' | 'DELETE'
2
3
enum Resource {
4
Person = 'Person',
5
Product = 'Product',
6
Sale = 'Sale',
7
}
8
9
// the `Lowercase` type concerts all string type options to lowercase
10
type ResourceAction = `${Resource}.${Action}`

Such that the ResourceAction type is now defined as:

1
type ResourceAction =
2
| 'Person.UPDATE'
3
| 'Person.CREATE'
4
| 'Person.DELETE'
5
| 'Product.UPDATE'
6
| 'Product.CREATE'
7
| 'Product.DELETE'
8
| 'Sale.UPDATE'
9
| 'Sale.CREATE'
10
| 'Sale.DELETE'

Now, if you’re like me - you probably want your types to be consistent in some way. For this purpose, we can use the Lowercase type as follows:

1
type ResourceActionLowercase = Lowercase<`${Resource}.${Action}`>

Which results in the following types:

1
type ResourceActionLowercase =
2
| 'person.update'
3
| 'person.create'
4
| 'person.delete'
5
| 'product.update'
6
| 'product.create'
7
| 'product.delete'
8
| 'sale.update'
9
| 'sale.create'
10
| 'sale.delete'