0
0
Typescriptprogramming~5 mins

Template literal types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a template literal type in TypeScript?
A template literal type lets you create new string types by combining other string literal types or string unions using backticks (`) and placeholders (${...}). It works like string templates but for types.
Click to reveal answer
beginner
How do you create a template literal type that combines two string literals, e.g., 'hello' and 'world'?
You write: `type Greeting = `${'hello'} ${'world'}`;` This creates a type that matches the string 'hello world'.
Click to reveal answer
intermediate
Can template literal types use unions inside placeholders? Give an example.
Yes. For example: `type Colors = 'red' | 'blue'; type Shades = `${Colors}Light` | `${Colors}Dark`;` This creates types like 'redLight', 'redDark', 'blueLight', and 'blueDark'.
Click to reveal answer
intermediate
What happens if you use a template literal type with a number or boolean type inside the placeholder?
TypeScript converts the number or boolean to a string literal type. For example, `type NumStr = `${1 | 2}`;` creates a type '1' | '2' as strings.
Click to reveal answer
beginner
Why are template literal types useful in TypeScript?
They help create flexible and precise string types by combining smaller types. This improves type safety and auto-completion for strings that follow patterns.
Click to reveal answer
Which syntax correctly defines a template literal type combining 'foo' and 'bar'?
Atype T = `${'foo'}${'bar'}`;
Btype T = 'foo' + 'bar';
Ctype T = 'foo' & 'bar';
Dtype T = 'foo' | 'bar';
What type does this produce? `type T = `${'a' | 'b'}${'1' | '2'}`;`
A'a' | 'b' | '1' | '2'
B'a1' | 'a2' | 'b1' | 'b2'
C'a12' | 'b12'
D'a' & '1' & 'b' & '2'
Can template literal types include expressions other than string literals?
AYes, but only boolean types
BNo, only string literals are allowed
CYes, including unions of strings and numbers converted to strings
DNo, only numbers are allowed
What is the result type of `type T = `${number}`;`?
Astring
Bnever
Cnumber
Dtemplate literal type representing any number as string
Why use template literal types instead of plain string unions?
ATo build complex string patterns from smaller parts
BTo allow any string value
CTo convert numbers to booleans
DTo disable type checking
Explain what template literal types are and how they help in TypeScript.
Think about how string templates work in JavaScript but for types.
You got /3 concepts.
    Describe how unions inside template literal types create multiple string combinations.
    Consider how 'a' | 'b' and '1' | '2' combine in a template literal.
    You got /3 concepts.