Logo Typescript Strict

Typescript Strict

Cộng đồng
citypaul
typescript-strict

TypeScript strict mode patterns including schema-first development, branded types, type vs interface guidance, and tsconfig strict flags. Use when writing TypeScript code, defining types or schemas, or reviewing type safety. For immutability and pure function patterns, see the functional skill.

Tổng quan

Nhà phát hànhcitypaul
Kho mã.dotfiles
Tên kỹ năngtypescript-strict
Sao
740
Bản fork
96
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được citypaul công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Typescript Strict trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/citypaul/.dotfiles/tree/main/claude/.claude/skills/typescript-strict
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/citypaul/.dotfiles.git /tmp/.dotfiles
mkdir -p .claude/skills
cp -r /tmp/.dotfiles/claude/.claude/skills/typescript-strict .claude/skills/typescript-strict
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Typescript Strict trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Typescript Strict ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Typescript Strict với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

TypeScript Strict Mode

Core Rules

  1. Use unknown at untrusted boundaries. Contain unavoidable any in external declarations or interop shims and explain it
  2. No type assertions (as Type) without justification
  3. Follow the repository's type/interface convention. Choose from language semantics when no convention exists
  4. Derive a value set that already has an owner; never spell it a second time. Before writing a literal union, an enum list, or a ===/|| chain over fixed values, search the codebase for that set — if a type, an as const list, or a schema already declares it, derive from that one owner

Type vs Interface

type — unions, tuples, mapped types, and closed aliases

typescript
export type User = {
  readonly id: string;
  readonly email: string;
  readonly name: string;
  readonly roles: ReadonlyArray<string>;
};

Type aliases can name unions, intersections, tuples, primitives, mapped types, and object shapes. They cannot be reopened through declaration merging.

interface — extendable object contracts

typescript
export interface UserRepository {
  findById(id: string): Promise<User | undefined>;
  save(user: User): Promise<void>;
}

Interfaces describe object shapes, work with implements, extend with conflict checking, and support declaration merging. They are useful for behavior contracts and deliberately open extension points, but are not forbidden for data shapes.

Schema Duplication

Define a schema once per owned contract, version, and bounded context, then import it within that boundary. Do not couple independently deployed consumers or contexts merely because their fields happen to match today; validate and translate at each trust boundary, with contract tests where drift matters.

Inside one boundary this is a search, not a judgement call. When a compile-time type and a runtime schema both need the same fixed set of values, one as const list owns it and both derive from that list. If the set is already declared as a hand-written union, widen that declaration and derive from it — do not leave a second copy of the members behind in the schema.

typescript
// ✅ One owner; the type and the schema both derive from it
export const ORDER_STATES = ['draft', 'placed', 'shipped'] as const;
export type OrderState = (typeof ORDER_STATES)[number];
export const OrderStateSchema = z.enum(ORDER_STATES);

// ❌ Two owners for one set; they drift apart the first time a value is added
export type OrderState = 'draft' | 'placed' | 'shipped';
export const OrderStateSchema = z.enum(['draft', 'placed', 'shipped']);
typescript
// ✅ Define once for this API contract
export const CreateUserRequestSchema = z.object({
  email: z.email(),
  name: z.string().min(1),
});
export type CreateUserRequest = z.infer<typeof CreateUserRequestSchema>;

// Import and use wherever needed

Where schemas belong: validate at trust boundaries (HTTP handlers, queue consumers, file/env parsing, third-party API responses), then pass plain derived types through internal logic — internal functions trust their inputs. Prefer schema libraries implementing Standard Schema (Zod 4+, Valibot, ArkType) so validation tooling stays interchangeable.


Strict Mode Configuration

tsconfig.json Settings

json
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noPropertyAccessFromIndexSignature": true,
    "forceConsistentCasingInFileNames": true,
    "allowUnusedLabels": false
  }
}

What Each Setting Does

Strict baseline:

  • strict: true - Enables the strict type-checking family, including noImplicitAny and strictNullChecks

Additional project checks:

  • noUnusedLocals - Error on unused local variables
  • noUnusedParameters - Error on unused function parameters
  • noImplicitReturns - Error when not all code paths return a value
  • noFallthroughCasesInSwitch - Error on fallthrough cases in switch statements

Additional safety flags to assess against the codebase:

  • noUncheckedIndexedAccess - Array/object access returns T | undefined (prevents runtime errors from assuming elements exist)
  • exactOptionalPropertyTypes - Distinguishes property?: T from property: T | undefined (more precise types)
  • noPropertyAccessFromIndexSignature - Requires bracket notation for index signature properties (forces awareness of dynamic access)
  • forceConsistentCasingInFileNames - Prevents case sensitivity issues across operating systems
  • allowUnusedLabels - Error on unused labels (catches accidental labels that do nothing)

Additional Rules

  • Prefer a justified, narrow @ts-expect-error over @ts-ignore when an upstream typing defect cannot yet be fixed
  • Apply the repository's type-safety policy to tests too; use deliberate test-only interop shims rather than weakening global configuration

Architectural Insight: noUnusedParameters Catches Design Issues

The noUnusedParameters rule can reveal architectural problems:

Example: A function with an unused parameter often indicates the parameter belongs in a different layer. Strict mode catches these design issues early.


Immutability, Pure Functions, and Composition

For detailed patterns on immutability (readonly, ReadonlyArray), pure functions, composition, Result types, array methods, and factory functions, see the functional skill. These are the canonical patterns used across the codebase.

Key TypeScript-specific notes:

  • Use readonly and ReadonlyArray<T> where immutability is part of the contract, especially shared domain values
  • The compiler enforces shallow property immutability; it does not make nested runtime values deeply immutable
  • Choose factories or classes from invariant, lifecycle, and project-convention needs; dependency injection does not require either form

Schema-First at Trust Boundaries

When Runtime Schemas Are Required

A runtime schema is required when untrusted data crosses a boundary and the program must validate its shape or constraints before using it. Common signals include:

  • HTTP, queue, file, environment, or third-party data entering the system
  • A data contract exchanged between independently deployed systems
  • Contract-shaped test fixtures where reusing an existing production schema adds useful evidence

Internal invariants do not require a schema by default. A smart constructor, branded type, or domain value object may be the clearer owner when values are created and consumed inside one trusted process.

typescript
// API responses, user input, external data
const UserSchema = z.object({
  id: z.uuid(),
  email: z.email(),
});
type User = z.infer<typeof UserSchema>;

// Validate at boundary
const user = UserSchema.parse(apiResponse);

When Schemas AREN'T Required

  • Pure internal types (utilities, state)
  • Result/Option types (no validation needed)
  • TypeScript utility types (Partial<T>, Pick<T>, etc.)
  • Behavior contracts (interfaces - structural, not validated)
  • Component props (unless from URL/API)
typescript
// ✅ CORRECT - No schema needed
type Result<T, E> =
  | { success: true; data: T }
  | { success: false; error: E };

// ✅ CORRECT - Interface, no validation
interface UserService {
  createUser(user: User): void;
}

Branded Types

Brand a primitive when two values of the same underlying type can be passed in each other's place and the compiler would not notice — two kinds of identifier, an amount and a rate, a raw and a normalised string. Validating each one at the boundary is not enough on its own: if the parsed values are still string afterwards, a swapped pair compiles everywhere downstream. Give each kind its own brand, confer it only where the value is validated, and declare the functions that consume them in terms of the brands rather than the primitive.

typescript
type UserId = string & { readonly brand: unique symbol };
type PaymentMinorUnits = number & { readonly brand: unique symbol };
type Currency = 'GBP' | 'USD' | 'EUR';
type PaymentMoney = {
  readonly minorUnits: PaymentMinorUnits;
  readonly currency: Currency;
};

// Type-safe at compile time
const processPayment = (userId: UserId, amount: PaymentMoney) => {
  // Implementation
};

// ❌ Can't pass raw string/number
processPayment('user-123', 100); // Error

// ✅ Brand via a validating constructor — the ONE place an assertion is justified
const toUserId = (raw: string): UserId => {
  if (raw.length === 0) throw new Error('UserId cannot be empty');
  return raw as UserId;
};
const toPaymentMinorUnits = (raw: number): PaymentMinorUnits => {
  if (!Number.isSafeInteger(raw) || raw <= 0) {
    throw new Error('Payment minor units must be a positive safe integer');
  }
  return raw as PaymentMinorUnits;
};
const toPaymentMoney = (minorUnits: number, currency: Currency): PaymentMoney => ({
  minorUnits: toPaymentMinorUnits(minorUnits),
  currency,
});

processPayment(toUserId('user-123'), toPaymentMoney(2_500, 'GBP')); // £25.00

Never scatter as UserId through application code — the assertion lives only inside the constructor (or a schema's transform), so every branded value has passed validation.

The payment boundary above accepts already-rounded integer minor units, so NaN, infinities, and binary-float fractions are rejected. If a boundary instead accepts decimal major-unit text, parse it with the currency's minor-unit exponent and a named rounding policy (or reject excess precision); never use Math.round(rawNumber * 100).


Summary Checklist

When writing TypeScript code, verify:

  • No unexplained any; unavoidable interop is narrow and contained
  • No type assertions without justification
  • type and interface follow repository convention or the required language semantics
  • Schemas have one owner per contract/version/context; independent boundaries are not coupled by convenience
  • A fixed value set the codebase already declares is derived from, never spelled a second time
  • Interchangeable same-typed primitives (identifiers, amounts, codes) are branded, each brand conferred only where the value is validated
  • strict is enabled; additional compiler checks follow the repository's adopted policy
  • For immutability, pure functions, composition: see functional skill

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

Kỹ năng AI Typescript Strict làm được gì?

TypeScript strict mode patterns including schema-first development, branded types, type vs interface guidance, and tsconfig strict flags. Use when writing TypeScript code, defining types or schemas, or reviewing type safety. For immutability and pure function patterns, see the functional skill.

Vì sao nên dùng Typescript Strict trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Typescript Strict là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Typescript Strict trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/citypaul/.dotfiles/tree/main/claude/.claude/skills/typescript-strict. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Typescript Strict?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Typescript Strict với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Typescript Strict với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Typescript Strict có miễn phí không?

Kỹ năng này được citypaul phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇