TypeScript Flashcards
What are the benefits of using TypeScript over plain JavaScript in large-scale projects?
Static Typing: TypeScript adds static types, helping catch errors during development rather than runtime, making refactoring safer.
Better Tooling: TypeScript provides improved autocompletion, refactoring tools, and code navigation in editors like VS Code.
Code Maintainability: As projects grow, types act as self-documentation, making it easier for teams to understand the codebase.
Scalability: In large projects, strong typing helps prevent common errors (e.g., undefined, null reference errors) and improves collaboration between developers.
Can you explain how TypeScript interfaces differ from TypeScript types? When would you use one over the other?
Interfaces: Focused on describing the shape of an object. They can be extended (merged) across declarations, allowing for flexibility.
Types: More versatile, as they can represent not just object shapes but also unions, intersections, tuples, etc. Types cannot be reopened like interfaces.
When to Use:
Use interface when defining object shapes that may be extended or modified.
Use type for complex type compositions (unions, intersections) or when working with more advanced constructs like tuples and function types.
What’s the purpose of the unknown type in TypeScript, and how is it different from any?
unknown is a type-safe alternative to any. Unlike any, you can’t perform arbitrary operations on variables of type unknown without narrowing its type.
Example:
let x: unknown;
x = 10; // Fine
x.toFixed(); // Error: Object is of type ‘unknown’.
Use case: When you don’t know the type of a variable upfront (e.g., data from APIs), but you want to enforce type safety by checking its type before using it.
How does TypeScript’s Partial utility type work, and in what scenarios would you use it?
The Partial<T> utility makes all properties of a type T optional. For example:
interface User {
name: string;
age: number;
}
const updateUser: Partial<User> = { name: "Alice" };
Use case: When updating objects partially (e.g., in forms, APIs where only part of the object needs to be modified).</User></T>