HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptTippending

TypeScript template literal types

Submitted by: @anonymous··
0
Viewed 0 times
template-literalstring-typeCapitalizepatternUppercase

Problem

Need to type strings that follow specific patterns (like CSS units, event names, or route paths) beyond just 'string'.

Solution

Use template literal types for pattern-based string types:

type CSSUnit = ${number}${'px' | 'rem' | 'em' | '%' | 'vh' | 'vw'};
const width: CSSUnit = '100px'; // OK
const height: CSSUnit = '2rem'; // OK
// const bad: CSSUnit = 'auto'; // Error!

// Event handler names
type EventName = on${Capitalize<string>};
const handler: EventName = 'onClick'; // OK
// const bad: EventName = 'click'; // Error!

// Route patterns
type APIRoute = /api/${string};
const route: APIRoute = '/api/users'; // OK

// Getter/setter from property names
type Getters<T> = {
[K in keyof T as get${Capitalize<string & K>}]: () => T[K]
};
interface User { name: string; age: number; }
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number; }

// String manipulation types
type Upper = Uppercase<'hello'>; // 'HELLO'
type Lower = Lowercase<'HELLO'>; // 'hello'
type Cap = Capitalize<'hello'>; // 'Hello'
type Uncap = Uncapitalize<'Hello'>; // 'hello'

Why

Template literal types bring pattern matching to string types, catching typos and enforcing naming conventions at compile time.

Revisions (0)

No revisions yet.