typescript-strict

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript 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 projectDebugging runtime errors (use debugger)
Migrating to stricter type safetyConfiguring build tools (use bundler docs)
Choosing moduleResolution strategyWriting application logic
Enabling noUncheckedIndexedAccessOptimizing 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: true
(总开关)

Enables 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
strict: true
for new projects.
启用所有严格类型检查选项:
json
{
  "strict": true
  // Equivalent to:
  // "noImplicitAny": true,
  // "strictNullChecks": true,
  // "strictFunctionTypes": true,
  // "strictBindCallApply": true,
  // "strictPropertyInitialization": true,
  // "noImplicitThis": true,
  // "alwaysStrict": true
}
新项目请始终启用
strict: true

Additional Strict Flags (Recommended for 2025)

2025年推荐的额外严格配置项

FlagPurpose
noUncheckedIndexedAccess
Index signatures return
T | undefined
instead of
T
noImplicitOverride
Require
override
keyword for overridden methods
noPropertyAccessFromIndexSignature
Force bracket notation for index signatures
noFallthroughCasesInSwitch
Prevent fallthrough in switch statements
exactOptionalPropertyTypes
Optional properties cannot be set to
undefined
explicitly
配置项作用
noUncheckedIndexedAccess
索引签名返回值类型为
T | undefined
而非
T
noImplicitOverride
重写父类方法时必须显式使用
override
关键字
noPropertyAccessFromIndexSignature
访问索引签名属性时必须使用方括号写法
noFallthroughCasesInSwitch
禁止switch语句中出现case穿透
exactOptionalPropertyTypes
可选属性不可被显式赋值为
undefined

noUncheckedIndexedAccess
(Essential)

noUncheckedIndexedAccess
(核心必备)

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
}
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

策略选择

StrategyUse ForExtensions Required
Bundler
Vite, Webpack, Bun projectsNo
NodeNext
Node.js libraries and serversYes (
.js
)
策略适用场景需要文件后缀
Bundler
Vite、Webpack、Bun项目不需要
NodeNext
Node.js库与服务端项目是(
.js

moduleResolution: "Bundler"
(Vite/Bun)

moduleResolution: "Bundler"
(适用于Vite/Bun)

json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler"
  }
}
  • No file extensions required in imports
  • JSON imports without assertions
  • Package.json
    exports
    field support
json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler"
  }
}
  • 导入时不需要加文件后缀
  • 导入JSON无需添加断言
  • 支持package.json
    exports
    字段

moduleResolution: "NodeNext"
(Node.js)

moduleResolution: "NodeNext"
(适用于Node.js)

json
{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext"
  }
}
  • Respects package.json
    type: "module"
  • Requires explicit
    .js
    extensions (even for
    .ts
    files)
  • 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
importsNotUsedAsValues
and
preserveValueImports
.
禁止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';
该配置项已替代已废弃的
importsNotUsedAsValues
preserveValueImports
配置。

Agentic Optimizations

快捷命令

ContextCommand
Check errors
bunx tsc --noEmit
Check single file
bunx tsc --noEmit src/utils.ts
Show config
bunx tsc --showConfig
Check module resolution
bunx tsc --showConfig | grep moduleResolution
场景命令
检查类型错误
bunx tsc --noEmit
检查单个文件
bunx tsc --noEmit src/utils.ts
查看生效配置
bunx tsc --showConfig
检查模块解析配置
bunx tsc --showConfig | grep moduleResolution

Quick Reference

快速参考

Recommended Flags

推荐配置项

FlagValueCategory
strict
true
Type Checking
noUncheckedIndexedAccess
true
Type Checking
noImplicitOverride
true
Type Checking
noPropertyAccessFromIndexSignature
true
Type Checking
noFallthroughCasesInSwitch
true
Type Checking
module
ESNext
/
NodeNext
Modules
moduleResolution
Bundler
/
NodeNext
Modules
verbatimModuleSyntax
true
Modules
target
ES2022
Emit
isolatedModules
true
Interop
skipLibCheck
true
Interop
For detailed examples, advanced patterns, and best practices, see REFERENCE.md.
配置项取值分类
strict
true
类型检查
noUncheckedIndexedAccess
true
类型检查
noImplicitOverride
true
类型检查
noPropertyAccessFromIndexSignature
true
类型检查
noFallthroughCasesInSwitch
true
类型检查
module
ESNext
/
NodeNext
模块配置
moduleResolution
Bundler
/
NodeNext
模块配置
verbatimModuleSyntax
true
模块配置
target
ES2022
编译输出
isolatedModules
true
兼容性配置
skipLibCheck
true
兼容性配置
如需详细示例、高级用法与最佳实践,请参考REFERENCE.md

References

参考资料