WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Advanced · question 53 of 100

What is ’strict mode’ in TypeScript and what does it do?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

Strict mode in TypeScript is a compiler option that enables a set of stricter type checking and safety features to help you write more robust, accurate, and maintainable code. It’s represented by the ‘–strict‘ flag in the ‘tsconfig.json‘ configuration file. When enabled, it activates several type checking and safety options, such as:

1. ‘noImplicitAny‘ - Disallows any implicit ‘any‘ types, forcing the programmer to provide type annotations.

2. ‘noImplicitThis‘ - Disallows using ‘this‘ in a function that’s not inside a class or object when the type is not known.

3. ‘alwaysStrict‘ - Enforces the use of ’use strict’ directive; parses ECMAScript modules in strict mode.

4. ‘strictNullChecks‘ - Disallows assigning ‘null‘ or ‘undefined‘ to non-nullable types.

5. ‘strictFunctionTypes‘ - Tightens the type checking for functions, ensuring that they are of compatible types.

6. ‘strictBindCallApply‘ - Ensures a more accurate type checking for ‘bind‘, ‘call‘, and ‘apply‘ methods.

7. ‘strictPropertyInitialization‘ - Ensures that class properties are initialized in the constructor, either directly or indirectly.

You can enable strict mode in the ‘tsconfig.json‘ file like this:

{
  "compilerOptions": {
    "strict": true
  }
}

Here’s an example to further illustrate the difference strict mode can make:

class Sample {
  name: string; // Without strict mode, this can be left uninitialized

  constructor(name?: string) {
    if (name) {
      this.name = name;
    }
  }

  printName() {
    console.log(this.name.toUpperCase());
  }
}

let instance = new Sample();
instance.printName(); // Throws a runtime error, since `name` is undefined

When strict mode is enabled, TypeScript will report an error on the ‘name‘ property because it’s not initialized. To fix this issue, you either need to provide a default value or declare it as a nullable type:

class Sample {
  name: string = "default"; // Provide a default value, or declare it as `string | undefined`

  constructor(name?: string) {
    if (name) {
      this.name = name;
    }
  }

  printName() {
    console.log(this.name.toUpperCase());
  }
}

In conclusion, strict mode helps you catch potential issues in your code during the development and compilation stages, thus ensuring your code is more robust and maintainable.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics