In this tutorial, we aim to give you a deep dive into the Advanced Template Literal Types in TypeScript. By mastering this advanced feature, you will be able to create complex, dynamic types that can significantly increase the flexibility and expressiveness of your code.
By the end of this tutorial, you will:
Prerequisites:
- Basic knowledge of TypeScript
- Understanding of TypeScript's basic types
In TypeScript 4.1, Template Literal Types was introduced. This is a powerful feature that allows you to create dynamic types using template literals syntax. Template Literal Types can be combined with union types, conditional types, etc., to create complex types.
Let's start with a basic example:
type World = "world";
type Greeting = `hello ${World}`; // "hello world"
Here, a Template Literal Type Greeting
is created by concatenating "hello" and the type World
.
Let's dive into more practical examples.
type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
type PropertyType<T, V extends JSONValue> = `${T & string} ${V extends string ? '(string)' : 'number'}`;
type MyType = PropertyType<'age', 20>; // "age number"
type AnotherType = PropertyType<'name', 'John'>; // "name (string)"
In this example, we define a type PropertyType
that takes two type parameters T
and V
and returns a new type that is a template literal.
type Flatten<T> = T extends any[] ? T[number] : T;
type Test = Flatten<[1, 2, 3]>; // 1 | 2 | 3
Here, we use Template Literal Types with conditional types to flatten an array type into a union of its element types.
In this tutorial, we dived deep into TypeScript's Template Literal Types, exploring how to create dynamic types and how to combine them with other features like conditional types.
For further learning, consider exploring other TypeScript features like mapped types, and how they can be combined with Template Literal Types.
Create a type Join
that concatenates an array of string types into a single string type. For example, Join<['1', '2', '3']>
should result in "123"
.
type Join<T extends string[]> = T extends [] ? '' : T extends [infer F, ...infer R] ? `${F & string}${Join<R & string[]>}` : never;
type Test = Join<['1', '2', '3']>; // "123"
Create a type ToArray
that transforms a string
or number
type to an array of that type. For example, ToArray<string>
should result in string[]
.
type ToArray<T extends string | number> = T[];
type Test = ToArray<string>; // string[]
Keep experimenting and practicing with more complex examples to solidify your understanding. Happy coding!