Here is a list of 50 TypeScript questions along with their answers, ranging from basic to advanced topics:
1. What is TypeScript?
Answer: TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It adds features like static typing, classes, interfaces, and more.
2. How is TypeScript different from JavaScript?
Answer: TypeScript adds static typing, interfaces, generics, and object-oriented programming features to JavaScript. It compiles to JavaScript, allowing for better tooling and error checking.
3. What are the benefits of using TypeScript?
Answer: TypeScript helps catch errors during development, improves code readability and maintainability, offers better tooling with autocompletion and refactoring, and supports modern JavaScript features.
4. What is the tsconfig.json
file?
Answer: The tsconfig.json
file is a configuration file for the TypeScript compiler. It specifies compiler options, files to include, and project settings.
5. How do you compile a TypeScript file?
Answer: Use the tsc
command followed by the file name, e.g., tsc file.ts
, or run tsc
to compile files defined in tsconfig.json
.
6. What is type inference in TypeScript?
Answer: TypeScript automatically infers the type of a variable based on its assigned value, reducing the need for explicit type declarations.
7. What is the any
type in TypeScript?
Answer: The any
type disables type checking for a variable, allowing it to hold any type of value. It’s best to avoid any
to maintain strong typing.
8. What is the unknown
type in TypeScript?
Answer: The unknown
type is similar to any
, but it requires a type check before performing operations on the variable, making it safer than any
.
9. What is the never
type in TypeScript?
Answer: The never
type represents a value that never occurs, such as in a function that always throws an error or never returns.
10. What is the void
type in TypeScript?
Answer: The void
type is used to indicate that a function does not return a value.
11. What are TypeScript interfaces?
Answer: Interfaces in TypeScript define the structure of an object, including property types and method signatures.
12. How do you make properties optional in an interface?
Answer: Append a question mark (?
) to the property name in the interface to make it optional.
13. What are generics in TypeScript?
Answer: Generics allow functions, classes, or interfaces to work with various types while keeping strong type-checking.
14. What is the difference between interface
and type
?
Answer: Both can define object types, but interface
is extendable and can merge declarations, whereas type
is more flexible with union types and aliases.
15. What are union types in TypeScript?
Answer: Union types allow a variable to hold multiple types, e.g., let value: string | number
.
16. What are intersection types in TypeScript?
Answer: Intersection types combine multiple types into one, meaning the variable must satisfy all the combined types, e.g., type A & B
.
17. How do you define default parameters in TypeScript functions?
Answer: Use the =
symbol in the parameter list to define a default value, e.g., function greet(name: string = "Guest")
.
18. What are decorators in TypeScript?
Answer: Decorators are special functions that modify the behavior of classes, methods, properties, or parameters.
19. What is readonly
in TypeScript?
Answer: The readonly
modifier ensures that a property can only be assigned a value once, either during initialization or in the constructor.
20. What is an enum in TypeScript?
Answer: Enums allow you to define a set of named constants, either numeric or string-based.
21. How do you define a tuple in TypeScript?
Answer: A tuple is an array with fixed types and length, e.g., let tuple: [string, number] = ["hello", 10]
.
22. What is the difference between ==
and ===
in TypeScript?
Answer: ==
compares values after type coercion, whereas ===
compares both value and type without coercion (strict equality).
23. What is type assertion in TypeScript?
Answer: Type assertion tells the compiler to treat a variable as a specific type, using either as
or the angle bracket syntax <Type>
.
24. What is strictNullChecks
in TypeScript?
Answer: When enabled, strictNullChecks
ensures that null
and undefined
are treated as separate types, preventing accidental null reference errors.
25. How do you handle null or undefined values in TypeScript?
Answer: Use union types (string | null | undefined
) or the optional chaining (?.
) and nullish coalescing operator (??
).
26. What are mapped types in TypeScript?
Answer: Mapped types create new types by transforming the properties of an existing type, e.g., type Readonly<T> = { readonly [P in keyof T]: T[P] };
.
27. How do you use the Partial
utility type in TypeScript?
Answer: The Partial
type makes all properties in an object type optional, e.g., Partial<T>
.
28. What is the Pick
utility type in TypeScript?
Answer: The Pick
utility type constructs a new type by picking a set of properties from an existing type, e.g., Pick<T, "prop1" | "prop2">
.
29. What is Omit
in TypeScript?
Answer: Omit
constructs a type by removing certain properties from an existing type, e.g., Omit<T, "prop1" | "prop2">
.
30. What is the Record
utility type in TypeScript?
Answer: Record<K, T>
creates a type with keys of type K
and values of type T
, e.g., Record<string, number>
.
31. What is the Required
utility type in TypeScript?
Answer: The Required
utility type makes all properties of an object type required, e.g., Required<T>
.
32. What is a discriminated union in TypeScript?
Answer: A discriminated union uses a common literal property to differentiate between multiple object types in a union.
33. How does TypeScript handle function overloading?
Answer: Function overloading allows you to define multiple function signatures, with the implementation provided in the final signature.
34. What is this
typing in TypeScript?
Answer: this
typing refers to specifying the type of this
within a function or class, ensuring correct method chaining or context.
35. How do you create an abstract class in TypeScript?
Answer: Use the abstract
keyword to define abstract classes and methods that must be implemented by derived classes.
36. What is the keyof
keyword in TypeScript?
Answer: keyof
is used to get a union of the property keys of a given type, e.g., keyof T
.
37. What is the infer
keyword in TypeScript?
Answer: infer
is used in conditional types to infer a type from the context, commonly used in advanced type manipulation.
38. How does async
/await
work in TypeScript?
Answer: async
/await
is used to work with promises, allowing you to write asynchronous code that looks synchronous.
39. What are ambient declarations in TypeScript?
Answer: Ambient declarations are used to tell TypeScript about the types of libraries or code that exist outside the current file, usually in *.d.ts
files.
40. What are type guards in TypeScript?
Answer: Type guards are expressions that narrow down the type of a variable within a conditional block, e.g., typeof
, instanceof
.
41. How do you handle third-party JavaScript libraries without TypeScript definitions?
Answer: Use @types
packages, create custom *.d.ts
declaration files, or use any
as a last resort.
42. What is the moduleResolution
option in tsconfig.json
?
Answer: moduleResolution
specifies how TypeScript should resolve module imports, with options like node
and classic
.
43. **What is
the difference between interface
and abstract class
in TypeScript?**
Answer: An interface
defines a contract for the structure of an object, while an abstract class
can define both the structure and the implementation.
44. What is the difference between let
, const
, and var
in TypeScript?
Answer: var
has function scope and allows hoisting, let
has block scope, and const
also has block scope but requires initialization and disallows reassignment.
45. What is the difference between public
, private
, and protected
in TypeScript?
Answer: public
allows access from anywhere, private
restricts access to within the class, and protected
allows access within the class and its subclasses.
46. How does TypeScript support namespaces?
Answer: Namespaces are a way to organize code into a logical grouping, using the namespace
keyword. They help avoid global scope pollution.
47. What is module augmentation in TypeScript?
Answer: Module augmentation allows you to add new members to an existing module or interface, extending its functionality.
48. How do you create a readonly
tuple in TypeScript?
Answer: Prefix the tuple type with readonly
, e.g., readonly [string, number]
.
49. What is the NonNullable
utility type in TypeScript?
Answer: NonNullable<T>
excludes null
and undefined
from T
, ensuring the type contains only non-nullable values.
50. What is strict
mode in TypeScript?
Answer: Enabling strict
mode ("strict": true
in tsconfig.json
) enforces all strict type-checking options, such as noImplicitAny
, strictNullChecks
, and more.
Here are some common TypeScript interview questions that cover various topics such as basic syntax, advanced features, and real-world use cases. These questions can help you prepare for a TypeScript interview:
51. What is TypeScript, and how does it differ from JavaScript?
- Answer: TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It adds static typing, interfaces, and other object-oriented features, improving code scalability and development efficiency. TypeScript provides better tooling, such as autocompletion and type checking, compared to JavaScript.
52. What are TypeScript types, and why are they useful?
- Answer: TypeScript types define the shape and structure of data (like variables, function parameters, and return values). Types help catch errors early during development (compile time), reducing runtime bugs and making the code easier to maintain and refactor.
53. What are interfaces in TypeScript, and how do they differ from types?
- Answer: Interfaces in TypeScript define the structure of an object, including the types of its properties and methods. They can also define contracts for classes. While both interfaces and types can define the shape of an object, interfaces can be extended and merged more easily, whereas types are more flexible in some cases (e.g., union types). Example:
interface User {
name: string;
age: number;
}
54. What is Type Inference in TypeScript?
- Answer: TypeScript automatically infers the type of a variable based on the value assigned to it. This reduces the need to explicitly declare types for every variable while still maintaining strong type-checking. Example:
let num = 5; // TypeScript infers that num is of type number
55. What are TypeScript decorators, and when would you use them?
- Answer: Decorators are special types of declarations that can be attached to classes, methods, or properties to modify their behavior. They are often used in frameworks like Angular to handle metadata or dependency injection. There are four types of decorators: Class, Method, Property, and Parameter decorators.
56. What is the any
type in TypeScript, and when would you use it?
- Answer: The
any
type allows a variable to hold any type of value, disabling TypeScript’s type-checking for that variable. While it gives flexibility, it should be avoided because it can lead to runtime errors and negates the benefits of static typing.
57. What are Union Types and Intersection Types in TypeScript?
- Union Types: A union type allows a variable to hold values of multiple types.
#### Example:let value: string | number; value = "hello"; // valid value = 42; // valid
- Intersection Types: Intersection types combine multiple types into one, meaning the value must satisfy all the combined types.
#### Example:typescript interface A { name: string; } interface B { age: number; } let person: A & B = { name: "John", age: 30 };
58. What is the difference between interface
and type
in TypeScript?
- Answer: Both
interface
andtype
can be used to define the shape of an object in TypeScript, but there are key differences:- Interface: Can be extended or implemented in classes and allows merging declarations.
- Type: More flexible, can define union or intersection types, and alias primitive types.
type Name = string;
type User = { id: number; name: string; };
59. How does TypeScript handle optional parameters in functions?
- Answer: You can define optional parameters by appending a question mark (
?
) after the parameter name. These parameters may or may not be passed when calling the function. Example:
function greet(name: string, age?: number): string {
return age ? `${name} is ${age}` : `Hello, ${name}`;
}
60. What are generics in TypeScript, and how do they work?
- Answer: Generics allow you to create reusable code components that work with a variety of types, while still maintaining strong type-checking. It’s like a placeholder for a type that can be specified when the function or class is used. Example:
function identity(arg: T): T {
return arg;
}
let num = identity(5);
let str = identity("hello");
61. What is the unknown
type in TypeScript? How does it differ from any
?
- Answer: The
unknown
type is a safer alternative toany
. Variables of typeunknown
can hold any type of value, but unlikeany
, you must perform type checks before performing operations onunknown
types. Example:
let value: unknown = "hello";
if (typeof value === "string") {
console.log(value.toUpperCase()); // TypeScript allows this
}
62. What is never
in TypeScript, and when would you use it?
- Answer: The
never
type represents a value that will never occur, such as in a function that always throws an error or an infinite loop. It signifies that the function does not return anything. Example:
function throwError(message: string): never {
throw new Error(message);
}
63. Explain TypeScript’s readonly
modifier.
- Answer: The
readonly
modifier makes a property immutable after its initial assignment. You can only assign a value to areadonly
property when it is first declared or within a constructor in a class. Example:
class Person {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}
const john = new Person("John");
john.name = "Doe"; // Error: Cannot assign to 'name' because it is a read-only property.
64. How do you define and use Enums in TypeScript?
- Answer: Enums allow you to define a set of named constants, which can be either numeric or string-based. Example (Numeric Enum):
enum Direction {
Up = 1,
Down,
Left,
Right
}
let dir: Direction = Direction.Up;
#### Example (String Enum):
enum Status {
Success = "SUCCESS",
Error = "ERROR"
}
65. How does TypeScript’s strict
mode work?
- Answer: TypeScript’s
strict
mode is enabled viatsconfig.json
by setting"strict": true
. It enables all strict type-checking options, including:noImplicitAny
: Disallows variables with an implicitany
type.strictNullChecks
: Ensures thatnull
andundefined
are treated as distinct types.strictFunctionTypes
: Enforces strict checks for function parameter and return types.
66. What are Type Aliases in TypeScript, and how are they different from interfaces?
- Answer: Type Aliases create a new name for a type and can represent complex types such as unions or intersections, whereas interfaces are better suited for defining the shape of objects and class contracts. Type aliases cannot be extended like interfaces. Example:
type ID = string | number;
67. What is tsconfig.json
and why is it important?
- Answer:
tsconfig.json
is a configuration file that defines how the TypeScript compiler should compile your project. It includes options like specifying the target ECMAScript version, module system, file inclusions, and other compiler settings.
68. How do you handle TypeScript with third-party JavaScript libraries that don’t have type definitions?
- Answer: For libraries without type definitions, you can:
- Use
@types
packages if available. - Use
declare
to create custom type declarations. - Use
any
type as a last resort, but this sacrifices type safety.
- Use
69. Explain how typeof
and instanceof
work in TypeScript.
- Answer:
typeof
: Used to get the type of a variable or expression (e.g.,string
,number
,object
).instanceof
: Used to check if an object is an instance of a particular class.
if (typeof value === 'string') { ... }
if (obj instanceof MyClass) { ... }
70. **What is type assertion in TypeScript, and how is it
different from type casting?**
- Answer: Type assertion is a way to tell TypeScript to treat a variable as a specific type. Unlike type casting in other languages, it does not perform type conversion but rather tells the compiler to assume the type. This is useful when you have more information about a value than TypeScript’s type checker. Example:
let someValue: any = "Hello";
let strLength: number = (someValue as string).length;