Last active
January 4, 2022 20:32
-
-
Save over40dev/8acacca14b9bd378ab5f68d32aad9c69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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