typescript
Always use when working with Typescript projects.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
TypeScript Cheatsheet
Type-safe JavaScript with static typing and modern features.
Configuration
tsconfig.json (Strict)
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"lib": ["ESNext"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
},
"include": ["src"],
"exclude": ["node_modules"]
}
Type Definitions
Basic Types
let str: string = "hello";
let num: number = 42;
let bool: boolean = true;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ["age", 25];
let obj: { name: string; age: number } = { name: "John", age: 30 };
Advanced Types
// Union
type Status = "loading" | "success" | "error";
// Intersection
type User = Person & { email: string };
// Generics
function identity<T>(arg: T): T { return arg; }
// Utility types
type PartialUser = Partial<User>;
type ReadonlyUser = Readonly<User>;
type PickName = Pick<User, "name">;
type OmitEmail = Omit<User, "email">;
Interfaces vs Types
interface User {
name: string;
age: number;
}
type UserType = {
name: string;
age: number;
};
// Interface extends, type uses &
interface Admin extends User {
role: string;
}
Functions
// Function declaration
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const add = (a: number, b: number): number => a + b;
// Optional parameters
function greet(name: string, title?: string): string {
return title ? `${title} ${name}` : name;
}
// Rest parameters
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
// Function overloads
function format(input: string): string;
function format(input: number): string;
function format(input: string | number): string {
return String(input);
}
Classes
class Person {
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, ${this.name}`;
}
}
// Inheritance
class Employee extends Person {
role: string;
constructor(name: string, age: number, role: string) {
super(name, age);
this.role = role;
}
}
Generics
// Generic function
function wrap<T>(value: T): { value: T } {
return { value };
}
// Generic class
class Container<T> {
constructor(private value: T) {}
get(): T { return this.value; }
}
// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Type Guards
function isString(value: unknown): value is string {
return typeof value === "string";
}
function process(value: unknown) {
if (isString(value)) {
console.log(value.toUpperCase()); // value is string here
}
}
Error Handling
// Custom errors
class ValidationError extends Error {
constructor(public field: string, message: string) {
super(message);
this.name = "ValidationError";
}
}
// Result type
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
function safeParse(json: string): Result<unknown> {
try {
return { ok: true, value: JSON.parse(json) };
} catch (error) {
return { ok: false, error: error as Error };
}
}
Best Practices
- Use
strict: truein tsconfig - Avoid
any- useunknownor specific types - Prefer interfaces for object shapes
- Use branded types for primitives needing validation
- Make invalid states unrepresentable
- Type at boundaries (API inputs/outputs)
- Use JSDoc for complex types
Compilation
tsc # Compile
tsc --noEmit # Type check only
tsc --project tsconfig.json # Specific config
# Watch mode (use tmux for background)
tmux new -d -s tsc 'tsc --watch'
Tips
-
tsc --noEmitfor fast type checking - Gradual adoption with
allowJs: true - Path mapping for clean imports:
"@/*": ["src/*"] - Declaration files:
"declaration": true - Source maps:
"sourceMap": true
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-01-20
- 索引更新时间
- 2026-01-26
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!