ProgrammingFrontend Developer

Explain how TypeScript implements strict typing compared to JavaScript. What are the main differences, and what does this feature provide in large projects?

Pass interviews with Hintsage AI assistant

Answer.

TypeScript is a superset of JavaScript that implements static (strict) typing. This means that type checking occurs at compile time rather than at runtime, as in JavaScript.

Main differences:

  • Static type checking: variables, function parameters, and return values can be explicitly defined.
  • Default types (type inference): implicitly determines the type of a variable based on the assigned value.
  • API unification: IDEs and code analysis tools can show types, autocomplete fields, and warn about errors.

Advantages in large projects:

  • A unified standard leads to fewer bugs.
  • Refactoring is faster and safer.
  • Team collaboration is simplified.

Example:

type User = { name: string; age: number; } function greet(user: User): string { return 'Hello, ' + user.name; } const u: User = { name: 'Ivan', age: 30 }; greet(u); // Ok

Trick question.

Question: Can you declare a variable of type any in a TypeScript project, and will the project lose the benefits of strict typing?

Answer:

Yes, TypeScript allows the use of the any type, which is equivalent to having no type checking for that variable. If any is used frequently, it negates the main advantage of TypeScript — strict typing, and you risk encountering typical runtime errors just like in JavaScript.

Example:

let data: any = 'test'; data = 42; // No error will occur, but it may cause issues

Examples of real errors caused by ignorance of the nuances of the topic.


Story

A developer frequently used the any type for complex objects to "get ahead faster". As a result, one day an object arrived with missing fields, and the application crashed unexpectedly: the error went to production because of the lack of type checking.


Story

In a large project, two different microservices were exchanging messages. One of the services changed the structure of the object, but TypeScript did not warn about this since the type was explicitly set as any. The bug was discovered a month later due to user complaints.


Story

A young developer did not specify the return type of a public function, relying on automatic type inference. After refactoring on the other side, the expected types ceased to work, leading to a chain of bugs throughout the project.