Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
// Error: Variable 'user' is used before being assignedletuser: User;
if (shouldFetchUser) {
console.log(user.name); // Error!
}
// Fixed: Initialize or use optional chainingletuser: User | undefined;
if (shouldFetchUser) {
console.log(user?.name);
}
更严格的返回类型检查
改进了检测函数在期望泛型类型时返回 null/undefined 的能力:
// Error in TS 5.7+: Function may return undefinedfunction getData<T>(): T {
const data = fetchData();
if (!data) return; // Error: undefined not assignable to Treturn data as T;
}
// Fixed: Proper type handlingfunction getData<T>(): T | undefined {
const data = fetchData();
data ? (data T) : ;
}
return
as
undefined
性能改进
通过改进的编译缓存加快构建时间
针对大型联合类型优化类型检查
改进 monorepo 的增量编译
扩展 Node.js 支持,改进模块解析
开发标准(2025)
严格模式配置
始终使用严格模式 - 它应成为 2025 年的默认设置:
{"compilerOptions":{// Enable all strict type-checking options"strict":true,// Individual strict flags (included in "strict": true)"strictNullChecks":true,"strictFunctionTypes":true,"strictBindCallApply":true,"strictPropertyInitialization":true,"noImplicitThis":true,"alwaysStrict":true,// Additional safety"noImplicitAny":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"noUncheckedIndexedAccess":true,"noUnusedLocals":true,"noUnusedParameters":true,"exactOptionalPropertyTypes":true,// ESM for 2025"module":"NodeNext","moduleResolution":"NodeNext","target":"ES2022",// Import helpers for smaller bundles"importHelpers":true,"esModuleInterop":true,"skipLibCheck":true,"forceConsistentCasingInFileNames":true}}
// Runtime type checking with type predicatesinterfaceUser {
type: 'user';
name: string;
email: string;
}
interfaceAdmin {
type: 'admin';
name: string;
permissions: string[];
}
typePerson = User | Admin;
// Type guard functionfunctionisAdmin(person: Person): person is Admin {
return person.type === 'admin';
}
functionhandlePerson(person: Person) {
if (isAdmin(person)) {
// TypeScript knows person is Admin hereconsole.log(person.permissions);
} else {
// TypeScript knows person is User hereconsole.log(person.email);
}
}
// Assertion function (throws on failure)functionassertIsAdmin(person: Person): asserts person is Admin {
if (person.type !== 'admin') {
thrownewError('Not an admin');
}
}
functionrequireAdmin(person: Person) {
assertIsAdmin(person);
// TypeScript knows person is Admin after this lineconsole.log(person.permissions);
}
类型缩小模式
// Truthiness narrowingfunctionprocessValue(value: string | null | undefined) {
if (value) {
// value is stringconsole.log(value.toUpperCase());
}
}
// typeof narrowingfunctionformatValue(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toFixed(2);
}
// instanceof narrowingfunctionhandleError(error: Error | string) {
if (error instanceofError) {
console.log(error.stack);
} else {
console.log(error);
}
}
// in operator narrowingtypeFish = { swim: () =>void };
typeBird = { fly: () =>void };
functionmove(animal: Fish | Bird) {
if ('swim'in animal) {
animal.swim();
} else {
animal.fly();
}
}
泛型编程
泛型约束
// Constrain to objects with 'id' propertyfunction findById<T extends { id: number }>(items: T[], id: number): T | undefined {
return items.find(item => item.id === id);
}
// Constrain to constructor typefunction createInstance<T>(constructor: new () => T): T {
returnnewconstructor();
}
// Multiple type parameters with constraintsfunction merge<T extendsobject, U extendsobject>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
// Default type parametersfunction createArray<T = string>(length: number, value: T): T[] {
returnArray(length).fill(value);
}
const strings = createArray(3, 'hello'); // string[]const numbers = createArray(3, 42); // number[]
泛型工具类型
// Pick specific propertiestypeUserPreview = Pick<User, 'id' | 'name'>;
// Omit specific propertiestypeUserWithoutPassword = Omit<User, 'password'>;
// Make all properties optionaltypePartialUser = Partial<User>;
// Make all properties requiredtypeRequiredUser = Required<PartialUser>;
// Make all properties readonlytypeImmutableUser = Readonly<User>;
// Extract function parameter typestypeParams = Parameters<typeof fetchUser>;
// Create object type from uniontypeStatus = 'idle' | 'loading' | 'success' | 'error';
typeStatusMap = Record<Status, { message: string }>;
异步模式与 Promise 类型
适当的异步错误处理
// Type-safe async result typetypeResult<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
asyncfunctionfetchUserSafe(id: number): Promise<Result<User>> {
try {
const response = awaitfetch(`/api/users/${id}`);
const data = await response.json();
return { success: true, data };
} catch (error) {
return {
success: false,
error: error instanceofError ? error : newError(String(error))
};
}
}
// Usage with type narrowingconst result = awaitfetchUserSafe(1);
if (result.success) {
console.log(result.data.name); // TypeScript knows data exists
} else {
console.error(result.error.message); // TypeScript knows error exists
}
# Build all projects with references
tsc --build
# Watch mode for development
tsc --build --watch
# Clean build artifacts
tsc --build --clean
性能优化
大型代码库的编译器选项
{"compilerOptions":{// Skip type checking of declaration files"skipLibCheck":true,// Incremental compilation"incremental":true,"tsBuildInfoFile":"./.tsbuildinfo",// Faster builds in monorepos"composite":true,// Import helpers once"importHelpers":true,// Skip default lib checks"skipDefaultLibCheck":true}}
类型导入优化
// Use type imports to help tree-shakingimporttype { User, Post } from'./types';
import { fetchUser } from'./api';
// Inline type imports (TypeScript 5.0+)import { fetchUser, typeUser } from'./api';