typescript-advanced-types
预览截图
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "typescript-advanced-types":https://skillpi.com/zh/skills/deepskill-d73648853cd2695d3e595ac0583eb5a04bb4b73b5c49b3c29451b03a706c0b22。安装前核对上游来源和版本:https://github.com/midudev/autoskills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
掌握 TypeScript 高级类型系统(包括泛型、条件类型、映射类型、模板字面量类型与工具类型),用于构建类型安全的应用。适用于实现复杂类型逻辑、创建可复用的类型工具或在 TypeScript 项目中确保编译时类型安全。
介绍来源: third_party · midudev · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- Master TypeScript的高级类型系统,包括通用型,有条件型,映射型,模板字元,以及用于构建类型安全应用的通用类型. 在执行复杂类型逻辑时使用,创建可重复使用的类型工具,或在TypeScript项目中确保编译时间类型安全.
- 适合谁
- 构建类型安全库或框架 创建可重复使用的通用组件 实施复杂类型推断逻辑 设计类型安全API客户端 构建形式验证系统 创建强类型配置对象 实施类型安全状态管理 将 JavaScript 代码库迁移到 TypeScript
- 实测状态
- 未测试
文件浏览
Frontmatter
name: typescript-advanced-types
description: Master TypeScript's advanced type system including generics, conditional types, mapped types, template literals, and utility types for building type-safe applications. Use when implementing complex type logic, creating reusable type utilities, or ensuring compile-time type safety in TypeScript projects.TypeScript Advanced Types
Comprehensive guidance for mastering TypeScript's advanced type system including generics, conditional types, mapped types, template literal types, and utility types for building robust, type-safe applications.
When to Use This Skill
- Building type-safe libraries or frameworks
- Creating reusable generic components
- Implementing complex type inference logic
- Designing type-safe API clients
- Building form validation systems
- Creating strongly-typed configuration objects
- Implementing type-safe state management
- Migrating JavaScript codebases to TypeScript
Core Concepts
1. Generics
Purpose: Create reusable, type-flexible components while maintaining type safety.
Basic Generic Function:
function identity<T>(value: T): T {
return value;
}
const num = identity<number>(42); // Type: number
const str = identity<string>("hello"); // Type: string
const auto = identity(true); // Type inferred: boolean
Generic Constraints:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(item: T): T {
console.log(item.length);
return item;
}
logLength("hello"); // OK: string has length
logLength([1, 2, 3]); // OK: array has length
logLength({ length: 10 }); // OK: object has length
// logLength(42); // Error: number has no length
Multiple Type Parameters:
function merge<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
const merged = merge({ name: "John" }, { age: 30 });
// Type: { name: string } & { age: number }
2. Conditional Types
Purpose: Create types that depend on conditions, enabling sophisticated type logic.
Basic Conditional Type:
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
Extracting Return Types:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: 1, name: "John" };
}
type User = ReturnType<typeof getUser>;
// Type: { id: number; name: string; }
Distributive Conditional Types:
type ToArray<T> = T extends any ? T[] : never;
type StrOrNumArray = ToArray<string | number>;
// Type: string[] | number[]
Nested Conditions:
type TypeName<T> = T extends string
? "string"
: T extends number
? "number"
: T extends boolean
? "boolean"
: T extends undefined
? "undefined"
: T extends Function
? "function"
: "object";
type T1 = TypeName<string>; // "string"
type T2 = TypeName<() => void>; // "function"
3. Mapped Types
Purpose: Transform existing types by iterating over their properties.
Basic Mapped Type:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface User {
id: number;
name: string;
}
type ReadonlyUser = Readonly<User>;
// Type: { readonly id: number; readonly name: string; }
Optional Properties:
type Partial<T> = {
[P in keyof T]?: T[P];
};
type PartialUser = Partial<User>;
// Type: { id?: number; name?: string; }
Key Remapping:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// Type: { getName: () => string; getAge: () => number; }
Filtering Properties:
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K];
};
interface Mixed {
id: number;
name: string;
age: number;
active: boolean;
}
type OnlyNumbers = PickByType<Mixed, number>;
// Type: { id: number; age: number; }
4. Template Literal Types
Purpose: Create string-based types with pattern matching and transformation.
Basic Template Literal:
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// Type: "onClick" | "onFocus" | "onBlur"
String Manipulation:
type UppercaseGreeting = Uppercase<"hello">; // "HELLO"
type LowercaseGreeting = Lowercase<"HELLO">; // "hello"
type CapitalizedName = Capitalize<"john">; // "John"
type UncapitalizedName = Uncapitalize<"John">; // "john"
Path Building:
type Path<T> = T extends object
? {
[K in keyof T]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never;
}[keyof T]
: never;
interface Config {
server: {
host: string;
port: number;
};
database: {
url: string;
};
}
type ConfigPath = Path<Config>;
// Type: "server" | "database" | "server.host" | "server.port" | "database.url"
5. Utility Types
Built-in Utility Types:
// Partial<T> - Make all properties optional
type PartialUser = Partial<User>;
// Required<T> - Make all properties required
type RequiredUser = Required<PartialUser>;
// Readonly<T> - Make all properties readonly
type ReadonlyUser = Readonly<User>;
// Pick<T, K> - Select specific properties
type UserName = Pick<User, "name" | "email">;
// Omit<T, K> - Remove specific properties
type UserWithoutPassword = Omit<User, "password">;
// Exclude<T, U> - Exclude types from union
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
// Extract<T, U> - Extract types from union
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
// NonNullable<T> - Exclude null and undefined
type T3 = NonNullable<string | null | undefined>; // string
// Record<K, T> - Create object type with keys K and values T
type PageInfo = Record<"home" | "about", { title: string }>;
Advanced Patterns
Pattern 1: Type-Safe Event Emitter
type EventMap = {
"user:created": { id: string; name: string };
"user:updated": { id: string };
"user:deleted": { id: string };
};
class TypedEventEmitter<T extends Record<string, any>> {
private listeners: {
[K in keyof T]?: Array<(data: T[K]) => void>;
} = {};
on<K extends keyof T>(event: K, callback: (data: T[K]) => void): void {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event]!.push(callback);
}
emit<K extends keyof T>(event: K, data: T[K]): void {
const callbacks = this.listeners[event];
if (callbacks) {
callbacks.forEach((callback) => callback(data));
}
}
}
const emitter = new TypedEventEmitter<EventMap>();
emitter.on("user:created", (data) => {
console.log(data.id, data.name); // Type-safe!
});
emitter.emit("user:created", { id: "1", name: "John" });
// emitter.emit("user:created", { id: "1" }); // Error: missing 'name'
Pattern 2: Type-Safe API Client
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
type EndpointConfig = {
"/users": {
GET: { response: User[] };
POST: { body: { name: string; email: string }; response: User };
};
"/users/:id": {
GET: { params: { id: string }; response: User };
PUT: { params: { id: string }; body: Partial<User>; response: User };
DELETE: { params: { id: string }; response: void };
};
};
type ExtractParams<T> = T extends { params: infer P } ? P : never;
type ExtractBody<T> = T extends { body: infer B } ? B : never;
type ExtractResponse<T> = T extends { response: infer R } ? R : never;
class APIClient<Config extends Record<string, Record<HTTPMethod, any>>> {
async request<Path extends keyof Config, Method extends keyof Config[Path]>(
path: Path,
method: Method,
...[options]: ExtractParams<Config[Path][Method]> extends never
? ExtractBody<Config[Path][Method]> extends never
? []
: [{ body: ExtractBody<Config[Path][Method]> }]
: [
{
params: ExtractParams<Config[Path][Method]>;
body?: ExtractBody<Config[Path][Method]>;
},
]
): Promise<ExtractResponse<Config[Path][Method]>> {
// Implementation here
return {} as any;
}
}
const api = new APIClient<EndpointConfig>();
// Type-safe API calls
const users = await api.request("/users", "GET");
// Type: User[]
const newUser = await api.request("/users", "POST", {
body: { name: "John", email: "john@example.com" },
});
// Type: User
const user = await api.request("/users/:id", "GET", {
params: { id: "123" },
});
// Type: User
Pattern 3: Builder Pattern with Type Safety
type BuilderState<T> = {
[K in keyof T]: T[K] | undefined;
};
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
}[keyof T];
type IsComplete<T, S> =
RequiredKeys<T> extends keyof S
? S[RequiredKeys<T>] extends undefined
? false
: true
: false;
class Builder<T, S extends BuilderState<T> = {}> {
private state: S = {} as S;
set<K extends keyof T>(key: K, value: T[K]): Builder<T, S & Record<K, T[K]>> {
this.state[key] = value;
return this as any;
}
build(this: IsComplete<T, S> extends true ? this : never): T {
return this.state as T;
}
}
interface User {
id: string;
name: string;
email: string;
age?: number;
}
const builder = new Builder<User>();
const user = builder
.set("id", "1")
.set("name", "John")
.set("email", "john@example.com")
.build(); // OK: all required fields set
// const incomplete = builder
// .set("id", "1")
// .build(); // Error: missing required fields
Pattern 4: Deep Readonly/Partial
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object
? T[P] extends Function
? T[P]
: DeepReadonly<T[P]>
: T[P];
};
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object
? T[P] extends Array<infer U>
? Array<DeepPartial<U>>
: DeepPartial<T[P]>
: T[P];
};
interface Config {
server: {
host: string;
port: number;
ssl: {
enabled: boolean;
cert: string;
};
};
database: {
url: string;
pool: {
min: number;
max: number;
};
};
}
type ReadonlyConfig = DeepReadonly<Config>;
// All nested properties are readonly
type PartialConfig = DeepPartial<Config>;
// All nested properties are optional
Pattern 5: Type-Safe Form Validation
type ValidationRule<T> = {
validate: (value: T) => boolean;
message: string;
};
type FieldValidation<T> = {
[K in keyof T]?: ValidationRule<T[K]>[];
};
type ValidationErrors<T> = {
[K in keyof T]?: string[];
};
class FormValidator<T extends Record<string, any>> {
constructor(private rules: FieldValidation<T>) {}
validate(data: T): ValidationErrors<T> | null {
const errors: ValidationErrors<T> = {};
let hasErrors = false;
for (const key in this.rules) {
const fieldRules = this.rules[key];
const value = data[key];
if (fieldRules) {
const fieldErrors: string[] = [];
for (const rule of fieldRules) {
if (!rule.validate(value)) {
fieldErrors.push(rule.message);
}
}
if (fieldErrors.length > 0) {
errors[key] = fieldErrors;
hasErrors = true;
}
}
}
return hasErrors ? errors : null;
}
}
interface LoginForm {
email: string;
password: string;
}
const validator = new FormValidator<LoginForm>({
email: [
{
validate: (v) => v.includes("@"),
message: "Email must contain @",
},
{
validate: (v) => v.length > 0,
message: "Email is required",
},
],
password: [
{
validate: (v) => v.length >= 8,
message: "Password must be at least 8 characters",
},
],
});
const errors = validator.validate({
email: "invalid",
password: "short",
});
// Type: { email?: string[]; password?: string[]; } | null
Pattern 6: Discriminated Unions
type Success<T> = {
status: "success";
data: T;
};
type Error = {
status: "error";
error: string;
};
type Loading = {
status: "loading";
};
type AsyncState<T> = Success<T> | Error | Loading;
function handleState<T>(state: AsyncState<T>): void {
switch (state.status) {
case "success":
console.log(state.data); // Type: T
break;
case "error":
console.log(state.error); // Type: string
break;
case "loading":
console.log("Loading...");
break;
}
}
// Type-safe state machine
type State =
| { type: "idle" }
| { type: "fetching"; requestId: string }
| { type: "success"; data: any }
| { type: "error"; error: Error };
type Event =
| { type: "FETCH"; requestId: string }
| { type: "SUCCESS"; data: any }
| { type: "ERROR"; error: Error }
| { type: "RESET" };
function reducer(state: State, event: Event): State {
switch (state.type) {
case "idle":
return event.type === "FETCH"
? { type: "fetching", requestId: event.requestId }
: state;
case "fetching":
if (event.type === "SUCCESS") {
return { type: "success", data: event.data };
}
if (event.type === "ERROR") {
return { type: "error", error: event.error };
}
return state;
case "success":
case "error":
return event.type === "RESET" ? { type: "idle" } : state;
}
}
Type Inference Techniques
1. Infer Keyword
// Extract array element type
type ElementType<T> = T extends (infer U)[] ? U : never;
type NumArray = number[];
type Num = ElementType<NumArray>; // number
// Extract promise type
type PromiseType<T> = T extends Promise<infer U> ? U : never;
type AsyncNum = PromiseType<Promise<number>>; // number
// Extract function parameters
type Parameters<T> = T extends (...args: infer P) => any ? P : never;
function foo(a: string, b: number) {}
type FooParams = Parameters<typeof foo>; // [string, number]
2. Type Guards
function isString(value: unknown): value is string {
return typeof value === "string";
}
function isArrayOf<T>(
value: unknown,
guard: (item: unknown) => item is T,
): value is T[] {
return Array.isArray(value) && value.every(guard);
}
const data: unknown = ["a", "b", "c"];
if (isArrayOf(data, isString)) {
data.forEach((s) => s.toUpperCase()); // Type: string[]
}
3. Assertion Functions
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new Error("Not a string");
}
}
function processValue(value: unknown) {
assertIsString(value);
// value is now typed as string
console.log(value.toUpperCase());
}
Best Practices
- Use
unknownoverany: Enforce type checking - Prefer
interfacefor object shapes: Better error messages - Use
typefor unions and complex types: More flexible - Leverage type inference: Let TypeScript infer when possible
- Create helper types: Build reusable type utilities
- Use const assertions: Preserve literal types
- Avoid type assertions: Use type guards instead
- Document complex types: Add JSDoc comments
- Use strict mode: Enable all strict compiler options
- Test your types: Use type tests to verify type behavior
Type Testing
// Type assertion tests
type AssertEqual<T, U> = [T] extends [U]
? [U] extends [T]
? true
: false
: false;
type Test1 = AssertEqual<string, string>; // true
type Test2 = AssertEqual<string, number>; // false
type Test3 = AssertEqual<string | number, string>; // false
// Expect error helper
type ExpectError<T extends never> = T;
// Example usage
type ShouldError = ExpectError<AssertEqual<string, number>>;
Common Pitfalls
- Over-using
any: Defeats the purpose of TypeScript - Ignoring strict null checks: Can lead to runtime errors
- Too complex types: Can slow down compilation
- Not using discriminated unions: Misses type narrowing opportunities
- Forgetting readonly modifiers: Allows unintended mutations
- Circular type references: Can cause compiler errors
- Not handling edge cases: Like empty arrays or null values
Performance Considerations
- Avoid deeply nested conditional types
- Use simple types when possible
- Cache complex type computations
- Limit recursion depth in recursive types
- Use build tools to skip type checking in production
版本历史
-
v0.4.1
GitHub ↗
原版更新说明
### 🐛 Bug Fixes - fix(autoskills): stop multiSelect from duplicating lines on redraw [`cc80891`](https://github.com/midudev/autoskills/commit/cc80891)
-
v0.4.0
GitHub ↗
原版更新说明
### ⚠️ Breaking Changes - refactor(autoskills)!: drop Deno support [`d6f4301`](https://github.com/midudev/autoskills/commit/d6f4301) ### ✨ Features - feat(registry): re-review 41 pending skills with the new pipeline [`aff4e3c`](https://github.com/midudev/autoskills/commit/aff4e3c) - feat(sync): let an AI adjudicate flagged skills instead of a human [`98d42aa`](https://github.com/midudev/autoskills/commit/98d42aa) - fix(registry): add official FastAPI skill and merge duplicate techs [`f58a99c`](https://github.com/midudev/autoskills/commit/f58a99c) - feat(registry): sync skills and drop those removed upstream [`1228788`](https://github.com/midudev/autoskills/commit/1228788) - feat(autoskills): add ui command to browse installed skills [`1e5a14a`](https://github.com/midudev/autoskills/commit/1e5a14a) - Add fastmcp skill for Python MCP server development FastMCP is the standard Python framework for building MCP servers. This skill teaches production patterns verified against FastMCP 3.2.x, specifically addressing APIs that LLMs hallucinate (server.state, on_startup, context.name in middleware — none of which exist). Detection: 'fastmcp' pattern in pyproject.toml/requirements.txt Validation: 97.1% (agentskills.io spec checker) [`8caa407`](https://github.com/midudev/autoskills/commit/8caa407) - feat: add ElysiaJS support with skills registry documentation and icon [`b2e1400`](https://github.com/midudev/autoskills/commit/b2e1400) ### 📦 Other Changes - test(cli): ignore FORCE_COLOR when checking CLI output [`97692cd`](https://github.com/midudev/autoskills/commit/97692cd) - chore(release): skip merge commits in the changelog [`5ba3aa3`](https://github.com/midudev/autoskills/commit/5ba3aa3) - docs: document ui command, missing flags and the AI review [`0ad8885`](https://github.com/midudev/autoskills/commit/0ad8885) - chore(sync): review skills with Claude and accept --only lists [`5740dd0`](https://github.com/midudev/autoskills/commit/5740dd0) - perf(autoskills): download skill files in parallel [`0293487`](https://github.com/midudev/autoskills/commit/0293487) - build(deps): update Astro 7, Tailwind, oxc, TypeScript 7 and pnpm [`18de798`](https://github.com/midudev/autoskills/commit/18de798)
-
v0.3.6
GitHub ↗
原版更新说明
### ✨ Features - feat(autoskills): detect instantdb projects [`c86be97`](https://github.com/midudev/autoskills/commit/c86be97) - feat(autoskills): detect bash scripts [`fe57ba0`](https://github.com/midudev/autoskills/commit/fe57ba0) ### 🐛 Bug Fixes - fix(autoskills): normalize registry paths for downloads [`8477028`](https://github.com/midudev/autoskills/commit/8477028) ### 📦 Other Changes - chore(registry): update synced skill manifest [`442cf12`](https://github.com/midudev/autoskills/commit/442cf12) - chore(registry): sync turborepo skill [`3fadf74`](https://github.com/midudev/autoskills/commit/3fadf74) - chore(registry): sync backend and rails skills [`db3b50b`](https://github.com/midudev/autoskills/commit/db3b50b) - chore(registry): sync frontend and mobile skills [`49550f5`](https://github.com/midudev/autoskills/commit/49550f5)
-
v0.3.5
GitHub ↗
原版更新说明
### ✨ Features - feat(cli): surface skill security warnings [`aba2acf`](https://github.com/midudev/autoskills/commit/aba2acf) - feat(autoskills): display registry security checks [`df77e04`](https://github.com/midudev/autoskills/commit/df77e04) - feat(swiftui): support selecting xctrace runs [`050801e`](https://github.com/midudev/autoskills/commit/050801e) - feat(rails-upgrade): add legacy guide and ci sync workflow [`468fde3`](https://github.com/midudev/autoskills/commit/468fde3) - feat(cloudflare): add flagship feature flag references [`f1b429d`](https://github.com/midudev/autoskills/commit/f1b429d) - feat(azure-diagnostics): add app service and messaging guides [`260ddd4`](https://github.com/midudev/autoskills/commit/260ddd4) - feat(autoskills): add curated Bun skill [`2760757`](https://github.com/midudev/autoskills/commit/2760757) ### 🐛 Bug Fixes - fix(ui): hide single selection group header [`e5c26da`](https://github.com/midudev/autoskills/commit/e5c26da) ### 📦 Other Changes - chore(skills): refresh registry skill guidance [`5d301d5`](https://github.com/midudev/autoskills/commit/5d301d5)
-
v0.3.4
GitHub ↗
原版更新说明
### ✨ Features - feat(autoskills): add verbose install tracing [`cc409f8`](https://github.com/midudev/autoskills/commit/cc409f8) - feat(autoskills): fall back to main registry mirror [`f7d9155`](https://github.com/midudev/autoskills/commit/f7d9155) ### 🐛 Bug Fixes - fix(release): normalize repository URL for changelog and release summary links [`832819e`](https://github.com/midudev/autoskills/commit/832819e) ### 📦 Other Changes - style(autoskills): format code for improved readability [`a5a3f11`](https://github.com/midudev/autoskills/commit/a5a3f11)
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 覆盖TypeScript高级类型系统的核心概念,包括泛型、条件类型、映射类型、模板字面量类型和工具类型
- 提供6个高级实战模式,涵盖事件发射器、API客户端、构建器模式、深度只读/部分、表单验证和判别联合
- 包含完整的最佳实践指南和常见陷阱提醒,具有极高的实用价值
亮点
- 触发词精准完整,覆盖多种变体,边界清晰
- description明确指出了适用场景:实现复杂类型逻辑、创建可复用的类型工具、确保编译时类型安全
亮点
- Phase/步骤清晰,有出口条件,含端到端示例
- frontmatter完整,单文件≤500行
- 文档结构完整,包含When to Use、Core Concepts、Advanced Patterns、Best Practices等章节
亮点
- 工具来源明确,参数正确,覆盖主要异常
- 不可逆操作有确认机制
- 代码示例完整且类型安全,具有良好的执行可靠性
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。