Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

template-literal-types模板文字类型

Agent Skill

template-literal-types 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

593

周安装

8

GitHub Stars

2

下载量

65
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:template-literal-types(模板文字类型)
来源仓库:https://github.com/marius-townhouse/effective-typescript-skills
仓库路径:skills/template-literal-types
安装命令:
npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill template-literal-types
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill template-literal-types

简介

template-literal-types 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理时使用。

  • 适用于 TypeScript 前端项目、类型定义维护和代码规范检查场景。
  • 可辅助识别模板文字类型用法、优化类型推导和减少运行时错误。
  • 安装命令:npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill template-literal-types。
  • 使用前需确认权限范围、维护状态及是否触发联网或文件读写操作。

SKILL.md

Use Template Literal Types to Model DSLs and String Relationships

Overview

Template literal types bring the power of JavaScript template literals to TypeScript's type system. They allow you to model structured subsets of strings, parse domain-specific languages (DSLs), and capture relationships between string types. Combined with conditional types and the infer keyword, they enable sophisticated string manipulation at the type level.

This skill is essential for bringing type safety to string-heavy APIs and for building powerful type transformations.

When to Use This Skill

  • Modeling structured string patterns (IDs, paths, URLs)
  • Parsing domain-specific languages (CSS selectors, query languages)
  • Transforming string types (camelCase, snake_case conversion)
  • Validating string formats at compile time
  • Combining with mapped types for key transformations

The Iron Rule

Use template literal types to model structured string subsets and DSLs. Combine with infer for parsing and mapped types for transformations.

Detection

Watch for these opportunities:

// RED FLAGS - Untyped strings that could be precise
type EventType = string;  // Could be 'click' | 'hover' | etc.
function query(selector: string): Element;  // Could parse CSS selectors
type CSSProperty = string;  // Could validate property names

Basic Template Literal Types

// Match strings starting with a prefix
type PseudoString = `pseudo${string}`;
const science: PseudoString = 'pseudoscience';  // OK
const alias: PseudoString = 'pseudonym';        // OK
const physics: PseudoString = 'physics';        // Error!

// Match specific patterns
type DataAttribute = `data-${string}`;
type HTTPSUrl = `https://${string}`;
type VersionString = `v${number}.${number}.${number}`;

Index Signatures with Template Literals

// Allow data-* attributes while keeping type safety
interface Checkbox {
  id: string;
  checked: boolean;
  [key: `data-${string}`]: unknown;
}

const check: Checkbox = {
  id: 'subscribe',
  checked: true,
  'data-listIds': 'all-the-lists',  // OK
  value: 'yes',  // Error: not data-* and not known property
};

Parsing with infer

Extract parts of strings using conditional types with infer:

// Extract event name from handler type
type EventName<T> = T extends `on${infer Name}` ? Name : never;

type ClickEvent = EventName<'onClick'>;      // 'Click'
type HoverEvent = EventName<'onMouseEnter'>; // 'MouseEnter'
type BadEvent = EventName<'handleClick'>;   // never

// Extract path parameters
type PathParams<T> = T extends `/users/${infer UserId}/posts/${infer PostId}`
  ? { userId: UserId; postId: PostId }
  : never;

type Params = PathParams<'/users/123/posts/456'>;
// { userId: '123'; postId: '456' }

String Transformations

Build recursive types to transform strings:

// Convert snake_case to camelCase
type CamelCase<S extends string> =
  S extends `${infer Head}_${infer Tail}`
    ? `${Head}${Capitalize<CamelCase<Tail>>}`
    : S;

type T1 = CamelCase<'foo'>;           // 'foo'
type T2 = CamelCase<'foo_bar'>;      // 'fooBar'
type T3 = CamelCase<'foo_bar_baz'>;  // 'fooBarBaz'

// Apply to object keys
type CamelCaseKeys<T> = {
  [K in keyof T as CamelCase<K & string>]: T[K]
};

type SnakeCase = { user_name: string; email_address: string };
type Camel = CamelCaseKeys<SnakeCase>;
// { userName: string; emailAddress: string }

Real-World Example: CSS Selectors

// Enhance querySelector with precise types
type HTMLTag = keyof HTMLElementTagNameMap;

declare global {
  interface ParentNode {
    // Simple tag selector
    querySelector<TagName extends HTMLTag>(
      selector: TagName
    ): HTMLElementTagNameMap[TagName] | null;

    // Tag#id selector
    querySelector<TagName extends HTMLTag>(
      selector: `${TagName}#${string}`
    ): HTMLElementTagNameMap[TagName] | null;
  }
}

// Usage
const img = document.querySelector('img#hero');
// Type: HTMLImageElement | null
// Can access img?.src, img?.alt, etc.

const div = document.querySelector('div#container');
// Type: HTMLDivElement | null

Combining with Mapped Types

// Create event handler types from event names
type EventMap = {
  click: MouseEvent;
  keydown: KeyboardEvent;
  submit: SubmitEvent;
};

type EventHandlers<Events extends Record<string, Event>> = {
  [K in keyof Events as `on${Capitalize<K & string>}`]?:
    (event: Events[K]) => void;
};

type Handlers = EventHandlers<EventMap>;
// {
//   onClick?: (event: MouseEvent) => void;
//   onKeydown?: (event: KeyboardEvent) => void;
//   onSubmit?: (event: SubmitEvent) => void;
// }

Pressure Resistance Protocol

When pressured to use simple string types:

  1. Identify patterns: What structure do the strings have?
  2. Start simple: Use unions of literal types first
  3. Add templates: Use template literals for infinite but structured sets
  4. Consider parsing: Use infer to extract information
  5. Test edge cases: Ensure your types are accurate, not just precise

Red Flags

Anti-PatternWhy It's Bad
type ID = stringMisses validation opportunity
Complex template types without testingMay be inaccurate
Parsing without escape hatchesComplex selectors need fallback
Overly precise typesCan break legitimate use cases

Common Rationalizations

"String is good enough"

Reality: Template literals catch typos and invalid formats at compile time. 'user-123' vs 'users-123' can be caught immediately.

"This is too complex"

Reality: Start simple with prefix patterns, then add complexity as needed. Even basic template literals provide value.

"It will hurt performance"

Reality: Template literal types are evaluated at compile time. They have no runtime cost.

Quick Reference

PatternSyntaxUse Case
Prefix` data-${string} `data attributes
Suffix` ${string}Event `event names
Middle` ${string}.${string} `file extensions
Extract` on${infer Name} `parsing
Transform` ${Head}${Capitalize<Tail>} `camelCase

The Bottom Line

Template literal types bring type safety to string-heavy code. Use them to model structured strings, parse DSLs, and transform types. Combined with infer and mapped types, they enable powerful type-level string manipulation.

Reference

  • Effective TypeScript, 2nd Edition by Dan Vanderkam
  • Item 54: Use Template Literal Types to Model DSLs and Relationships Between Strings

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.64%
按下载量换算24

Claude

29.5%
按下载量换算19

Cursor

19.61%
按下载量换算13

Gemini CLI

9.62%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills