Statically Type String Literals with Template Literal Types in TypeScript

Marius Schulz
InstructorMarius Schulz

Share this video with your friends

Send Tweet

In this lesson, we're going to explore template literal types, another powerful feature of TypeScript's type system. Template literal types have the same syntax as template literals in JavaScript, but they're used in type positions. Using template literal types, we can produce a union of string literal types and perform string concatenation in the type space:

type Dimension = "block" | "inline";
type MarginProperty = `margin-${Dimension}`;

Additional Reading

~ a month ago

Would it be possible to do it without const newObj: any So the compiler would catch if you changed the implementation to e.g const getterKey = gets${capitalizedKey}`; I gave it a quick try but ran into too many issues...