Skip to content

Instantly share code, notes, and snippets.

@over40dev
Last active January 4, 2022 20:32
Show Gist options
  • Save over40dev/8acacca14b9bd378ab5f68d32aad9c69 to your computer and use it in GitHub Desktop.
Save over40dev/8acacca14b9bd378ab5f68d32aad9c69 to your computer and use it in GitHub Desktop.
// see YouTube video from Basarat (https://youtu.be/8KIkLPQPt98)
// Example 1 - Template Literal Types - Basic
let jsStringLiteral: string;
jsStringLiteral = 'Hello';
jsStringLiteral = 'World';
let jsTemplateLiteral: `Example: ${string}`; // Okay
jsTemplateLiteral = `Example: ${jsStringLiteral}`; // Okay
jsTemplateLiteral = `Example: ${3.14}`; // Okay
jsTemplateLiteral = `Examples: ${3.14}`; // Type Error
// Example 2 - Template Literal Types - TYPE|string combination
type CSSValue =
// implies px
| number
// number + px|em|rem
| `${number}px`
| `${number}em`
| `${number}rem`
function size(input: CSSValue) {
return typeof input == 'number' ? input + 'px' : input;
}
size(123);
// size(false); // Type Error
size('123px');
size('123em');
size('123rem');
size('123ex'); // Type Error
// Example 3 - Template Literal Types - Multi-Type combination
type Size = 'small' | 'medium' | 'large';
type Color = 'primary' | 'secondary'
type AppliedStyle = `${Size}-${Color}`;
/**
*
* @param style is a combination of
* Size: 'small' or 'medium' or 'large'
* Color: 'primary' or 'secondary'
* e.g. 'small-secondary'
*/
function applyStyle(style: AppliedStyle) {
}
applyStyle('small-primary'); // Okay
applyStyle('large-secondary'); // Okay
applyStyle('med-primary'); // Type Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment