typescript-strict
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Strict Mode
TypeScript严格模式
Modern TypeScript configuration with strict type checking for maximum safety and developer experience. This guide focuses on TypeScript 5.x best practices for 2025.
针对现代TypeScript的严格类型检查配置,可实现最大程度的类型安全与最优开发体验。本指南聚焦2025年TypeScript 5.x版本的最佳实践。
When to Use This Skill
适用场景
| Use this skill when... | Use another approach when... |
|---|---|
| Setting up a new TypeScript project | Debugging runtime errors (use debugger) |
| Migrating to stricter type safety | Configuring build tools (use bundler docs) |
| Choosing moduleResolution strategy | Writing application logic |
| Enabling noUncheckedIndexedAccess | Optimizing bundle size (use bundler skills) |
| 以下场景可使用本指南 | 以下场景请选择其他方案 |
|---|---|
| 搭建新的TypeScript项目 | 调试运行时错误(请使用调试器) |
| 迁移至更严格的类型安全规范 | 配置构建工具(请参考打包工具文档) |
| 选择moduleResolution策略 | 编写应用业务逻辑 |
| 启用noUncheckedIndexedAccess配置 | 优化打包体积(请使用打包工具相关技能) |
Core Expertise
核心特性
What is Strict Mode?
- Type safety: Catch more bugs at compile time
- Better IDE experience: Improved autocomplete and refactoring
- Maintainability: Self-documenting code with explicit types
- Modern defaults: Align with current TypeScript best practices
Key Capabilities
- Strict null checking
- Strict function types
- No implicit any
- No unchecked indexed access
- Proper module resolution
- Modern import/export syntax enforcement
什么是严格模式?
- 类型安全:在编译阶段捕获更多Bug
- 更优的IDE体验:更完善的自动补全与重构支持
- 可维护性:显式类型让代码实现自文档化
- 现代默认配置:与当前TypeScript最佳实践对齐
核心能力
- 严格空值检查
- 严格函数类型
- 禁用隐式any类型
- 禁用未检查的索引访问
- 合理的模块解析规则
- 现代import/export语法强制校验
Recommended tsconfig.json (2025)
2025年推荐tsconfig.json配置
Minimal Production Setup
最简生产环境配置
json
{
"compilerOptions": {
// Type Checking
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
// Modules
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": false,
"verbatimModuleSyntax": true,
// Emit
"target": "ES2022",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"removeComments": false,
"noEmit": false,
// Interop
"isolatedModules": true,
"allowJs": false,
"checkJs": false,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "build"]
}json
{
"compilerOptions": {
// Type Checking
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
// Modules
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": false,
"verbatimModuleSyntax": true,
// Emit
"target": "ES2022",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"removeComments": false,
"noEmit": false,
// Interop
"isolatedModules": true,
"allowJs": false,
"checkJs": false,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "build"]
}Strict Flags Explained
严格配置项详解
strict: true
(Umbrella Flag)
strict: truestrict: true
(总开关)
strict: trueEnables all strict type-checking options:
json
{
"strict": true
// Equivalent to:
// "noImplicitAny": true,
// "strictNullChecks": true,
// "strictFunctionTypes": true,
// "strictBindCallApply": true,
// "strictPropertyInitialization": true,
// "noImplicitThis": true,
// "alwaysStrict": true
}Always enable for new projects.
strict: true启用所有严格类型检查选项:
json
{
"strict": true
// Equivalent to:
// "noImplicitAny": true,
// "strictNullChecks": true,
// "strictFunctionTypes": true,
// "strictBindCallApply": true,
// "strictPropertyInitialization": true,
// "noImplicitThis": true,
// "alwaysStrict": true
}新项目请始终启用。
strict: trueAdditional Strict Flags (Recommended for 2025)
2025年推荐的额外严格配置项
| Flag | Purpose |
|---|---|
| Index signatures return |
| Require |
| Force bracket notation for index signatures |
| Prevent fallthrough in switch statements |
| Optional properties cannot be set to |
| 配置项 | 作用 |
|---|---|
| 索引签名返回值类型为 |
| 重写父类方法时必须显式使用 |
| 访问索引签名属性时必须使用方括号写法 |
| 禁止switch语句中出现case穿透 |
| 可选属性不可被显式赋值为 |
noUncheckedIndexedAccess
(Essential)
noUncheckedIndexedAccessnoUncheckedIndexedAccess
(核心必备)
noUncheckedIndexedAccesstypescript
// With noUncheckedIndexedAccess
const users: Record<string, User> = {};
const user = users['john'];
// Type: User | undefined (correct - must check before use)
if (user) {
console.log(user.name); // Type narrowed to User
}Always enable this flag to prevent runtime errors.
typescript
// With noUncheckedIndexedAccess
const users: Record<string, User> = {};
const user = users['john'];
// Type: User | undefined (correct - must check before use)
if (user) {
console.log(user.name); // Type narrowed to User
}请始终启用该配置项以避免运行时错误。
Module Resolution
模块解析
Choosing a Strategy
策略选择
| Strategy | Use For | Extensions Required |
|---|---|---|
| Vite, Webpack, Bun projects | No |
| Node.js libraries and servers | Yes ( |
| 策略 | 适用场景 | 需要文件后缀 |
|---|---|---|
| Vite、Webpack、Bun项目 | 不需要 |
| Node.js库与服务端项目 | 是( |
moduleResolution: "Bundler"
(Vite/Bun)
moduleResolution: "Bundler"moduleResolution: "Bundler"
(适用于Vite/Bun)
moduleResolution: "Bundler"json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Bundler"
}
}- No file extensions required in imports
- JSON imports without assertions
- Package.json field support
exports
json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Bundler"
}
}- 导入时不需要加文件后缀
- 导入JSON无需添加断言
- 支持package.json 字段
exports
moduleResolution: "NodeNext"
(Node.js)
moduleResolution: "NodeNext"moduleResolution: "NodeNext"
(适用于Node.js)
moduleResolution: "NodeNext"json
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext"
}
}- Respects package.json
type: "module" - Requires explicit extensions (even for
.jsfiles).ts - Supports conditional exports
json
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext"
}
}- 遵循package.json 配置
type: "module" - 导入需要显式添加后缀(即便原文件是
.js格式).ts - 支持条件导出
verbatimModuleSyntax (Recommended for 2025)
verbatimModuleSyntax(2025年推荐启用)
Prevents TypeScript from rewriting imports/exports.
json
{
"compilerOptions": {
"verbatimModuleSyntax": true
}
}typescript
// Error: 'User' is a type and must be imported with 'import type'
import { User } from './types';
// Correct
import type { User } from './types';
// Correct (mixed import)
import { fetchUser, type User } from './api';Replaces deprecated and .
importsNotUsedAsValuespreserveValueImports禁止TypeScript重写import/export语句。
json
{
"compilerOptions": {
"verbatimModuleSyntax": true
}
}typescript
// Error: 'User' is a type and must be imported with 'import type'
import { User } from './types';
// Correct
import type { User } from './types';
// Correct (mixed import)
import { fetchUser, type User } from './api';该配置项已替代已废弃的与配置。
importsNotUsedAsValuespreserveValueImportsAgentic Optimizations
快捷命令
| Context | Command |
|---|---|
| Check errors | |
| Check single file | |
| Show config | |
| Check module resolution | |
| 场景 | 命令 |
|---|---|
| 检查类型错误 | |
| 检查单个文件 | |
| 查看生效配置 | |
| 检查模块解析配置 | |
Quick Reference
快速参考
Recommended Flags
推荐配置项
| Flag | Value | Category |
|---|---|---|
| | Type Checking |
| | Type Checking |
| | Type Checking |
| | Type Checking |
| | Type Checking |
| | Modules |
| | Modules |
| | Modules |
| | Emit |
| | Interop |
| | Interop |
For detailed examples, advanced patterns, and best practices, see REFERENCE.md.
| 配置项 | 取值 | 分类 |
|---|---|---|
| | 类型检查 |
| | 类型检查 |
| | 类型检查 |
| | 类型检查 |
| | 类型检查 |
| | 模块配置 |
| | 模块配置 |
| | 模块配置 |
| | 编译输出 |
| | 兼容性配置 |
| | 兼容性配置 |
如需详细示例、高级用法与最佳实践,请参考REFERENCE.md。
References
参考资料
- TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/intro.html
- TSConfig Reference: https://www.typescriptlang.org/tsconfig
- Strict Mode Guide: https://www.typescriptlang.org/tsconfig#strict
- Module Resolution: https://www.typescriptlang.org/docs/handbook/module-resolution.html
- Best Practices: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
- TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/intro.html
- TSConfig Reference: https://www.typescriptlang.org/tsconfig
- Strict Mode Guide: https://www.typescriptlang.org/tsconfig#strict
- Module Resolution: https://www.typescriptlang.org/docs/handbook/module-resolution.html
- Best Practices: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html