Загрузка…
Загрузка…
TypeScript · middle · сложность 5
strict: true — не один флаг, а зонтик из ~8 независимых проверок. Главные: strictNullChecks (null/undefined больше не живут в каждом типе) и noImplicitAny (невыведенное не становится тихо any). Без strict TypeScript часто врёт; со strict типы начинают что-то значить.
strictNullChecks чинит «billion-dollar mistake»: без него user.name.toUpperCase() компилируется при user: null и падает в runtime.
strict включает семейство: strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, useUnknownInCatchVariables, alwaysStrict. Можно точечно выключать подфлаги при миграции.
Не входят в strict, но почти всегда нужны: noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitOverride, noFallthroughCasesInSwitch.
Как весь TS (кроме pragma "use strict"), флаги стираются — это compile-time контракт.
// tsconfig.json — the baseline every new project should ship
{
"compilerOptions": {
"strict": true,
// Not in `strict`, but you almost always want them:
"noUncheckedIndexedAccess": true, // arr[i] is T | undefined — forces bounds handling
"noImplicitOverride": true, // must write `override` when overriding
"noFallthroughCasesInSwitch": true
}
}// strictNullChecks OFF → this compiles and crashes at runtime:
function greet(name: string) { return name.toUpperCase(); }
greet(null); // ❌ no error without the flag; 💥 TypeError at runtime
// strictNullChecks ON → the compiler forces the guard:
function greetSafe(name: string | null) {
if (name == null) return "hi"; // ✅ must narrow first
return name.toUpperCase();
}
// noUncheckedIndexedAccess ON → the off-by-one the type system now catches:
const xs = [1, 2, 3];
const first = xs[0]; // type is number | undefined, not number
first.toFixed(); // ❌ error until you handle undefinedВключайте strict: true в новых проектах и добавьте noUncheckedIndexedAccess; без null-checks TypeScript даёт ложное чувство безопасности.