Web Development
TypeScript
Subjective
Oct 04, 2025
Explain template literal types and their use cases.
Detailed Explanation
Template literal types create string patterns at the type level for powerful string manipulation.
Basic Template Literals:
type World = 'world';
type Greeting = \`hello ${World}\`; // 'hello world'
type EmailLocaleIDs = 'welcome_email' | 'email_heading';
type FooterLocaleIDs = 'footer_title' | 'footer_sendoff';
type AllLocaleIDs = \`${EmailLocaleIDs | FooterLocaleIDs}_id\`;
// 'welcome_email_id' | 'email_heading_id' | 'footer_title_id' | 'footer_sendoff_id'
API Route Generation:
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Resource = 'users' | 'posts' | 'comments';
type APIRoute = \`/${Resource}\` | \`/${Resource}/${string}\`;
type RouteHandler = {
[K in HTTPMethod as \`${K} ${T}\`]: (req: Request) => Response;
};
// Usage
const handlers: Partial> = {
'GET /users': (req) => { /* ... */ },
'POST /users': (req) => { /* ... */ }
};
CSS-in-JS Type Safety:
type CSSProperties = {
color?: string;
backgroundColor?: string;
fontSize?: string;
};
type StyledComponent = {
[K in T as \`${K}Styled\`]: (props: CSSProperties) => JSX.Element;
};
// Generate styled components
type ButtonComponents = StyledComponent<'primary' | 'secondary'>;
// { primaryStyled: ..., secondaryStyled: ... }
Benefits:
• Type-safe string manipulation at compile time
• Generate API routes and handlers
• Create CSS-in-JS type safety
• Build complex string patterns
• Enable advanced metaprogramming.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts