Skip to content

Strict 模式 in TypeScript

启用 strict 编译器 flags 到 catch 大多数 bugs: 空检查, implicit 任何, and 更多.

你将学到

  • 什么 strict: 真启用 and 为什么它 是 recommended
  • Individual strict flags and 它们的特定 protections
  • 如何 migrate existing 项目到 strict 模式 incrementally
  • Additional strictness flags 超出 strict bundle

概念讲解

The Strict Bundle

Setting "strict": 真 in tsconfig.json enables a bundle of safety checks simultaneously. This includes strictNullChecks (null and undefined are not assignable to other types), noImplicitAny (parameters and variables must have explicit or inferable types), strictFunctionTypes (function parameter types are checked contravariantly), strictBindCallApply, strictPropertyInitialization (class properties must be initialized), noImplicitThis, and alwaysStrict (emits "use strict" in output).

Individual Flags

You can enable individual flags if you cannot adopt strict all at once. The most impactful is strictNullChecks — it alone prevents a huge class of runtime errors. noImplicitAny catches untyped parameters that would silently become 任何. strictPropertyInitialization ensures class properties are set in the constructor, catching uninitialized property bugs. Each flag can be toggled independently for gradual adoption.

Incremental Migration

Migrating an existing project to strict mode can produce many errors. The recommended approach is incremental: enable strictNullChecks first (it catches the most bugs), fix the errors, then enable noImplicitAny, and so on. You can also use // @ts-ignore or // @ts-expect-错误 to temporarily suppress specific errors while you work through them. The goal is full strict mode, but the path can be gradual.

示例代码

              // tsconfig.json — strict mode configuration.
{
  "compilerOptions": {
    // Option 1: Enable everything at once (recommended for new projects).
    "strict": true,

    // Option 2: Enable individual flags (for gradual migration).
    // "strictNullChecks": true,
    // "noImplicitAny": true,
    // "strictFunctionTypes": true,
    // "strictPropertyInitialization": true,
    // "noImplicitThis": true,
    // "alwaysStrict": true,

    // Additional strictness beyond the strict bundle.
    "noUnusedLocals": true,        // error on unused local variables
    "noUnusedParameters": true,    // error on unused parameters
    "noFallthroughCasesInSwitch": true, // error on switch fallthrough
    "noImplicitReturns": true,     // error on missing return paths
    "noUncheckedIndexedAccess": true    // arr[i] is T | undefined
  }
}

// With strict mode, the compiler catches these:
class User {
  name: string; // ❌ strictPropertyInitialization: not initialized
  constructor(public id: number) {}
}

function process(data: any) { // ❌ noImplicitAny: parameter is any
  return data.value;
}

// With noUncheckedIndexedAccess:
const arr: number[] = [1, 2, 3];
const item = arr[10]; // type: number | undefined
            

strict: 真启用 bundle 的 safety 检查. 大多数 impactful 是 strictNullChecks and noImplicitAny. Migrate incrementally 通过启用 flags one at 时间. Additional flags 如 noUnusedLocals 添加 further strictness.

动手试一试

  • Code Diff

    Compare code 那个通过 strict 模式使用 code 那个失败它.

  • Code Minifier

    Strict 模式 affects emitted code — alwaysStrict 添加 'use strict'.

常见错误

错误写法

开始新 项目不使用 strict 模式启用

正确做法

总是启用 strict: 真 in 新项目. Retrofitting strict 模式 later 是 much harder than 开始使用它. flags catch bugs 从 day one.

错误写法

Using @ts-ignore 到 suppress strict 模式错误相反的 fixing 它们

正确做法

@ts-ignore hides 错误不使用 fixing 它. Fix underlying 类型 issue. 如果 suppression 是 truly 必要, use @ts-expect-错误所以编译器 warns 如果错误 disappears.

练习 Strict 模式 in TypeScript

4 个练习

练习 Strict 模式 in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误