Functions and Classes Interview Questions
What are function overloads? When would you use them?
Multiple call signatures followed by one implementation signature. Use them when the return type depends on the argument types. If it does not, a union parameter is simpler.
Overloads
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]) {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]
console.log(one + 1, many.length);Output
43 2
What is the difference between private and #private?
private is a TypeScript-only check, erased at runtime: the property is still visible in JSON.stringify, console.log and via obj["x"]. #field is a JavaScript private field enforced by the runtime and invisible outside the class. private works with parameter properties (constructor(private repo: Repo)), which is why NestJS and Angular code uses it.
Abstract class vs interface?
An interface is a pure contract with no code and disappears at runtime. An abstract class exists at runtime, cannot be instantiated, and can mix implemented methods, fields and constructor logic with abstract methods that subclasses must implement. A class can implements many interfaces but extends only one class. Note: NestJS DI tokens must be runtime values, so abstract classes are sometimes used as injection tokens instead of interfaces.
What are parameter properties?
A shorthand where adding public, private, protected or readonly to a constructor parameter declares and assigns a property in one step.
class OrderService {
constructor(private readonly repo: OrderRepository, public readonly currency = "INR") {}
}
// same as declaring repo and currency fields and assigning them in the constructorHow do you type "this" and avoid losing it in callbacks?
Methods passed as callbacks lose this. Fix it with an arrow-function property (handle = () => {...}), .bind(this), or by wrapping in an arrow at the call site. You can also declare a this parameter (function f(this: Cart) {}) so the compiler checks the call context; it is erased in the output.