Chuyển đến nội dung
Skillpedia
Lập trình chung41k · #6715

typescript-advanced-types

Skill này làm gì

Hướng dẫn này chỉ cách dùng các tính năng kiểu dữ liệu nâng cao của TypeScript để tạo code an toàn và linh hoạt hơn. Nội dung gồm cách tạo kiểu thích ứng với nhiều loại dữ liệu (generics), tạo kiểu thay đổi theo điều kiện, biến đổi kiểu có sẵn, và tạo kiểu dựa trên chuỗi văn bản.

Khi nào nên dùng

  • ✓Khi bạn tạo các thư viện code để người khác sử dụng.
  • ✓Khi bạn cần code rất an toàn trước lỗi.
  • ✓Khi bạn xây dựng hệ thống phức tạp cần kiểu dữ liệu được định nghĩa rõ ràng.

Liên kết skill

https://github.com/wshobson/agents/blob/main/plugins/javascript-typescript/skills/typescript-advanced-types/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/wshobson/agents/blob/main/plugins/javascript-typescript/skills/typescript-advanced-types/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tạo một kiểu chỉ chấp nhận số hoặc chuỗi?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

TypeScript cho phép định nghĩa quy tắc cho kiểu dữ liệu. Các tính năng như generics và conditional types giúp tạo các quy tắc này tự động và linh hoạt, bảo đảm dữ liệu dùng là đúng ngay cả trước khi chương trình chạy.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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
  ? {

…
Câu hỏi thường gặp

Generics là gì?

Generics giống như các “chỗ giữ chỗ” cho kiểu dữ liệu. Chúng cho phép tạo hàm hoặc class hoạt động với bất kỳ kiểu dữ liệu nào, nhưng vẫn đảm bảo kiểu được dùng là đúng.

Conditional types là gì?

Đây là các kiểu hoạt động khác nhau tùy theo điều kiện. Ví dụ, một kiểu có thể là “true” nếu dữ liệu là chuỗi, và “false” nếu dữ liệu là số.

Template literal types dùng để làm gì?

Chúng cho phép tạo các kiểu dựa trên chuỗi, như tạo tên sự kiện (`onClick`) từ một tên gốc (`click`), hoặc tạo đường dẫn cấu hình một cách an toàn.

Chi tiết

Mô tả gốc của tác giả

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.

repo: wshobson/agents

Độ phổ biến

Sao GitHub
41k
Vị trí xếp hạng
#6715
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự