TypeScript Interview Questions
π‘ Click Show Answer to generate an AI-powered answer instantly.
What is TypeScript and why is it used?
TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of JavaScript, meaning it builds upon JavaScript by adding optional static typing and other features like interfaces, enums, and decorators. Ultimately, TypeScript code compiles down to plain JavaScript, allowing it to run in any JavaScript environment.
What is TypeScript?
TypeScript is essentially JavaScript with an added type system. While JavaScript is dynamically typed, TypeScript introduces the concept of static typing, where variables, function parameters, and return values can be explicitly defined with specific types (e.g., string, number, boolean, object).
This type system helps developers catch errors during development time, rather than at runtime, leading to more robust and predictable code. It allows for clearer intent and better understanding of the data structures within an application.
Why is TypeScript Used?
The adoption of TypeScript has grown significantly due to the numerous benefits it brings to software development, especially for large-scale applications and collaborative projects. Its primary goal is to make JavaScript development more scalable and maintainable.
- Improved Code Quality and Readability
- Better Tooling and IDE Support
- Early Bug Detection
- Enhanced Scalability and Maintainability
- Easier Collaboration
- Access to Modern JavaScript Features
Improved Code Quality and Readability
By requiring explicit type declarations, TypeScript makes the codebase more self-documenting. Developers can quickly understand what kind of data a function expects or returns, which reduces ambiguities and makes the code easier to read, understand, and refactor.
Better Tooling and IDE Support
The rich type information in TypeScript allows Integrated Development Environments (IDEs) and code editors (like VS Code) to provide superior autocompletion, refactoring tools, and navigation features. This significantly boosts developer productivity and reduces the mental overhead of remembering complex API structures.
Early Bug Detection
One of TypeScript's most compelling features is its ability to catch common programming errors at compile time, before the code even runs. Type mismatches, incorrect property access, or calling functions with wrong arguments are flagged immediately, preventing many runtime errors and saving debugging time.
Enhanced Scalability and Maintainability
For large applications with many modules and team members, TypeScript's static typing provides a safety net. Changes in one part of the code are less likely to break unrelated parts because the type system ensures consistency. This makes it easier to manage and refactor large codebases over time.
function greet(name: string): string {
return `Hello, ${name}!`;
}
let userName: string = "Alice";
console.log(greet(userName)); // Output: Hello, Alice!
// console.log(greet(123)); // This would be a compile-time error in TypeScript
What are basic types in TypeScript?
TypeScript is a strongly-typed superset of JavaScript that enhances code quality and maintainability by introducing static types. Understanding its basic types is fundamental for building robust applications.
Primitive Types
These are the simplest data types, directly corresponding to JavaScript's primitive values.
Boolean
Represents a logical entity and can have two values: true or false.
let isDone: boolean = false;
let hasStarted: boolean = true;
Number
As in JavaScript, all numbers in TypeScript are floating-point values. They can be decimal, hexadecimal, binary, or octal literals.
let decimal: number = 25;
let hex: number = 0xfd0;
let binary: number = 0b1011;
let octal: number = 0o723;
String
Represents text data. You can use single quotes, double quotes, or backticks (for template strings).
let studentName: string = "Alice";
let greeting: string = `Hello, ${studentName}!`;
Null and Undefined
TypeScript has null and undefined types. By default, they are subtypes of all other types, meaning you can assign null or undefined to number, string, etc. (unless --strictNullChecks is enabled).
let u: undefined = undefined;
let n: null = null;
// When --strictNullChecks is off:
let x: string = "value";
x = undefined; // OK
x = null; // OK
Symbol (ES6)
Introduced in ECMAScript 2015 (ES6), Symbol is a primitive value that represents a unique identifier.
let id1: symbol = Symbol('id');
let id2: symbol = Symbol('id');
// console.log(id1 === id2); // false
BigInt (ES2020)
Represents whole numbers larger than 2^53 - 1, which is the maximum value a number primitive can reliably represent.
let largeNumber: bigint = 1234567890123456789012345678901234567890n;
let anotherLargeNumber: bigint = BigInt("9007199254740991");
Other Fundamental Types
TypeScript also provides several other types that are crucial for building applications, often combining primitives or defining specific behaviors.
Array
Represents a collection of values of the same type. You can declare arrays using two syntaxes.
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["A", "B", "C"];
Tuple
Allows you to express an array where the type of a fixed number of elements is known, but does not have to be the same.
let user: [string, number];
user = ["John Doe", 30]; // OK
// user = [30, "John Doe"]; // Error
Enum
Enums provide a way of giving more friendly names to sets of numeric values. They can be numeric or string-based.
enum LoadState { Loading, Loaded, Error };
let currentState: LoadState = LoadState.Loaded;
enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT" };
Any
The any type is a powerful way to opt-out of type-checking for a particular value. Variables of type any can be reassigned to any type and can have any property accessed.
let untyped: any = 4;
untyped = "hello";
untyped = false;
untyped.someMethod(); // No error at compile time
Unknown
Similar to any, but safer. Values of type unknown must be narrowed through type checks before they can be used in operations that rely on a specific type.
let value: unknown = "TypeScript";
if (typeof value === 'string') {
console.log(value.toUpperCase()); // OK, 'value' is narrowed to string
}
// let s: string = value; // Error: Type 'unknown' is not assignable to type 'string'.
Void
Used for functions that do not return any value. It's the opposite of any.
function logMessage(message: string): void {
console.log(message);
}
Never
The never type represents the type of values that never occur. It's used for functions that always throw an exception or functions that never return (e.g., an infinite loop).
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}