Sub topic 2
What `"strict": true` Turns On
This chapter assumes basic TypeScript types, functions, classes, and terminal use. The strict option enables a group of compiler checks that catch unsafe assumptions before JavaScript runs.
What `"strict": true` turns on
strict is an umbrella option. It enables several stricter checks, including:
noImplicitAnystrictNullChecksstrictPropertyInitializationstrictFunctionTypesstrictBindCallApplynoImplicitThisuseUnknownInCatchVariablesalwaysStrict
Individual options can still be overridden when a project is migrating.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false
}
}`noImplicitAny`: no silent `any`
any disables most type checking. With noImplicitAny, TypeScript reports parameters whose types cannot be inferred.
function doubleTyped(x: number): number {
return x * 2;
}
console.log(doubleTyped(4));Without the annotation, function double(x) { ... } produces an implicit-any error. Add a type or give the function enough context for TypeScript to infer one.
`strictNullChecks`: handling `null` and `undefined`
With strictNullChecks, null and undefined are separate types. A value typed as string | null must be checked before string operations.
function safeLengthOf(text: string | null): number {
return text === null ? 0 : text.length;
}
console.log(safeLengthOf(null));
console.log(safeLengthOf("TypeScript"));`strictPropertyInitialization` in classes
Every required class property must receive a value in its declaration or constructor.
class User {
name: string;
email?: string;
constructor(name: string) {
this.name = name;
}
}
console.log(new User("Ari").name);The email property is optional. A required property left unassigned causes a compile-time error.
Stricter functions, `bind`, `call`, and `this`
strictFunctionTypes checks whether function parameter types are safely assignable. This prevents a callback that accepts only a narrower type from being used where a broader type is required.
strictBindCallApply checks arguments passed through bind, call, and apply. noImplicitThis requires TypeScript to understand a function's this value instead of silently treating it as any.
function label(prefix: string, count: number): string {
return `${prefix}: ${count}`;
}
const itemLabel = label.bind(null, "Items");
console.log(itemLabel(3));Exercise
Why does strictNullChecks reject value.toUpperCase() when value has type string | null?
Show answer
Because value might be null; check or narrow it before calling a string method.