javascript / expert
Snippet
Template Literal Type Constraints for Angular Component String Literal Datatypes
TypeScript Template Literal Types allow constructing strict string literal union datatypes derived from base string parameters (`ds-${ColorVariant}-${ComponentSize}`). In Angular component inputs, this enforces compile-time design system token compliance and works alongside custom type guards for runtime boundary assertion.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type ColorVariant = 'primary' | 'secondary' | 'accent';type ComponentSize = 'sm' | 'md' | 'lg';type DesignSystemToken = `ds-${ColorVariant}-${ComponentSize}`;import { Component, Input, booleanAttribute } from '@angular/core';@Component({selector: 'app-badge',standalone: true,template: `<span [class]="tokenClass">{{ label }}</span>`})export class BadgeComponent {@Input({ required: true }) label!: string;@Input({ required: true }) token!: DesignSystemToken;@Input({ transform: booleanAttribute }) disabled = false;get tokenClass(): string {return `badge-variant-${this.token}`;}static isValidToken(val: string): val is DesignSystemToken {return /^ds-(primary|secondary|accent)-(sm|md|lg)$/.test(val);}}
angular
Breakdown
1
type DesignSystemToken = `ds-${ColorVariant}-${ComponentSize}`;
Constructs a dynamic string literal datatype representing all 9 valid permutations of design tokens.
2
@Input({ required: true }) token!: DesignSystemToken;
Declares an Angular component input restricted strictly to valid DesignSystemToken string formatted values.
3
@Input({ transform: booleanAttribute }) disabled = false;
Uses Angular built-in input transform utility for coerced boolean attribute parsing.
4
static isValidToken(val: string): val is DesignSystemToken {
Provides a runtime custom type guard using regular expressions to narrow raw string primitives to the literal type.