1. Overview
This topic gathers exam-style TypeScript questions modeled on assessments spanning multiple modules of this course — basic types and classes through generics and advanced type manipulation. Use it as a final review before a module test or final exam: each question mimics the phrasing and depth an instructor might use, and each answer explains not just the 'what' but the reasoning the compiler applies, so you can transfer the logic to slightly different exam questions rather than memorizing answers verbatim.
Cricket analogy: This is like a batter reviewing every type of delivery -- yorkers, bouncers, googlies -- spanning basic types through generics, right before a big final, so no exam "delivery" is unfamiliar.
2. Frequently Asked Questions
Q1. Given `class Animal { protected name: string; constructor(name: string) { this.name = name; } }` and `class Dog extends Animal {}`, can code outside these classes access `dog.name`?
No. 'protected' members are accessible within the declaring class and any subclass, but not from outside the class hierarchy. Attempting dog.name from external code raises 'Property name is protected and only accessible within class Animal and its subclasses.' Only 'public' members (the default) are accessible everywhere; 'private' members are restricted to the exact declaring class, not even subclasses.
Cricket analogy: protected is like a technique only the batting family's coaching lineage can use -- accessible to the player and their direct successors, but a rival team can't call on it; private is stricter, usable only by the exact original coach; public is open to anyone watching.
Q2. What is the output type of `Partial<Point>` given `interface Point { x: number; y: number; }`?
Partial<Point> produces { x?: number; y?: number; }, making every property of Point optional. Partial is one of TypeScript's built-in mapped utility types, implemented internally as type Partial<T> = { [P in keyof T]?: T[P]; }. It is commonly used for update/patch functions where only a subset of fields needs to be supplied, e.g. function updatePoint(p: Point, patch: Partial<Point>): Point.
Cricket analogy: Partial<PlayerStats> making every field optional is like a mid-season update form where you only fill in the stats that changed -- say, just strike rate -- instead of resubmitting the entire player profile from scratch.
Q3. Trace this code: does it compile, and if so what is the type of 'area'? abstract class Shape { abstract area(): number; } class Circle extends Shape { constructor(private radius: number) { super(); } area(): number { return Math.PI * this.radius ** 2; } } const s: Shape = new Circle(2); const area = s.area();
It compiles successfully. Shape is an abstract class that cannot be instantiated directly ('new Shape()' would error), but Circle implements the abstract area() method, so 'new Circle(2)' is valid and can be assigned to a variable typed as the base class Shape. Calling s.area() calls Circle's implementation at runtime (polymorphism), and the compiler infers 'area' as type number because Shape.area() is declared to return number.
Cricket analogy: Shape as abstract is like "Bowler" being an abstract role you can never field directly -- you must field a concrete "Fast Bowler" (Circle), and the actual delivery style used at runtime is theirs, even though the scoreboard lists their type as "Bowler."
Q4. Write and explain a generic constraint that restricts T to types with a 'length' property.
function logLength<T extends { length: number }>(arg: T): T { console.log(arg.length); return arg; } uses 'extends' to constrain the generic parameter T so that only types with a numeric 'length' property (strings, arrays, or custom objects with a length field) are accepted. Calling logLength(42) fails to compile because number has no length property, while logLength('hello') and logLength([1,2,3]) both compile because string and array types satisfy the constraint.
Cricket analogy: function rankByOvers<T extends { overs: number }> constrains T so only bowling figures with an overs field are accepted -- passing a batting-only stat object fails to compile, the way you can't rank a player's "overs bowled" if they've never held the ball.
Q5. What type does `keyof Point` produce for `interface Point { x: number; y: number; }`, and where is it commonly used?
keyof Point produces the union of string literal types 'x' | 'y' — every known property name of Point. It is commonly used in generic accessor functions, e.g. function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }, which guarantees at compile time that 'key' is a valid property of 'obj' and that the return type matches that property's actual type (T[K], an indexed access type).
Cricket analogy: keyof PlayerStats producing 'runs' | 'wickets' | 'catches' is like a scoreboard listing only recognized stat columns; getStat<T, K extends keyof T>(player, key) guarantees at compile time you can only request a column that exists on that record, with the right type returned.
Q6. A student writes `let x: string | number = getValue(); if (typeof x === 'string') { x.toUpperCase(); }`. Explain why this compiles.
This is control-flow-based type narrowing. Outside the if block, x has the declared union type string | number, so calling toUpperCase() directly would fail because number has no such method. Inside the 'if (typeof x === "string")' branch, TypeScript's control flow analysis narrows x's type specifically to string, so x.toUpperCase() is valid there. Outside the branch (or in an else branch), x would be narrowed to number instead.
Cricket analogy: Outside an if (typeof x === "string") check, x holds string | number so calling .toUpperCase() on a run-total field would fail to compile; inside the branch, TypeScript narrows x to string, like a scorer reading a "not out" text label only once confirmed non-numeric.
Q7. What is the difference between a conditional type and a mapped type? Give one example of each.
A conditional type selects between two types based on a type-level condition, using the form T extends U ? X : Y; for example type IsString<T> = T extends string ? true : false;. A mapped type transforms every property of an existing type using an [P in keyof T] clause; for example type Readonly<T> = { readonly [P in keyof T]: T[P] }. Conditional types branch based on a check, while mapped types iterate over and transform an object type's properties — the two are often combined, e.g. in utility types like Exclude or Pick.
Cricket analogy: A conditional type like IsAllRounder<T> = T extends { bats: true; bowls: true } ? true : false branches based on a check, like a selector deciding "all-rounder or specialist" from skill flags; a mapped type like Readonly<PlayerCard> iterates over every stat field and locks each one, like a printed scorecard frozen after the match.
Q8. Given `enum Direction { Up, Down, Left, Right }`, what are the runtime values of Direction.Up and Direction.Down?
By default, numeric enums are auto-incremented starting at 0, so Direction.Up is 0 and Direction.Down is 1 (Left is 2, Right is 3). Unlike a plain union of string literals, a numeric enum is compiled into a real JavaScript object at runtime with both forward (Up -> 0) and reverse (0 -> 'Up') mappings, which is why numeric enums have a runtime footprint that literal-type unions do not.
Cricket analogy: A numeric enum enum FieldPosition { Slip, Gully, Point } auto-increments so Slip is 0 and Gully is 1, and unlike a plain union it compiles into a real object with both Slip -> 0 and 0 -> 'Slip' lookups -- a physical fielding chart queryable both ways.
Q9. Explain what `Record<'admin' | 'user', string[]>` produces and when you would use it.
Record<K, T> constructs an object type whose keys are exactly the union K and whose values all have type T. Record<'admin' | 'user', string[]> produces { admin: string[]; user: string[]; }. It is used whenever you need a lookup object with a known, finite set of keys and a consistent value type, such as role-to-permissions maps, ensuring at compile time that every key in the union is present and no extra keys are added.
Cricket analogy: Record<'batting' | 'bowling', string[]> producing { batting: string[]; bowling: string[]; } is like a fixed two-column stats sheet guaranteeing every team's file has exactly a batting list and a bowling list, no more, no fewer.
Q10. What compile error occurs here, and how would you fix it? class Base { greet(): void { console.log('hi'); } } class Derived extends Base { greet(name: string): void { console.log('hi ' + name); } }
This raises 'Property greet in type Derived is not assignable to the same property in base type Base' because Derived narrows the method signature incompatibly — Base.greet() takes zero arguments while Derived.greet(name: string) requires one, breaking the Liskov substitution guarantee that a Derived should be usable anywhere a Base is expected. The fix is to make the parameter optional (greet(name?: string): void) so Derived.greet() remains callable with zero arguments, matching Base's contract.
Cricket analogy: Derived.greet requiring a name argument while Base.greet takes none is like a fielder who can only take a catch if the captain shouts a specific instruction first -- but any "Base" fielder should be usable with zero setup; the fix is making the shout optional.
Q11. What is the inferred type of the parameter 'item' in `[1, 2, 3].map(item => item * 2)`, and why doesn't it need an annotation?
'item' is inferred as number through contextual typing: because [1, 2, 3] is typed as number[], TypeScript already knows the callback passed to .map() will receive a number, so it infers the parameter type from the array's element type without requiring an explicit annotation. This is a common exam trick question because students often assume unannotated parameters are implicitly 'any', but contextual typing from the surrounding call fills in the type automatically.
Cricket analogy: In [45, 67, 12].map(item => item * 2), item is inferred as number through contextual typing because the array is known to hold run totals, the way a scorer treats every entry on a numeric tally sheet as a number without re-checking each one.
Q12. Does the following compile? `function double(x: number | string) { return typeof x === 'number' ? x * 2 : x.repeat(2); }`
Yes, it compiles. The ternary's condition typeof x === 'number' narrows x to number in the 'true' branch, allowing x * 2, and by process of elimination narrows x to string in the 'false' branch, allowing x.repeat(2). This is exhaustive narrowing across a two-member union using typeof, a classic exam pattern for testing understanding of control-flow narrowing inside expressions, not just if-statements.
Cricket analogy: A ternary typeof x === 'number' ? x * 2 : x.repeat(2) narrows x to number in the true branch, allowing arithmetic on a run total, and by elimination narrows it to string in the false branch for a player's name -- exhaustive narrowing across the union.
3. Quick Reference
- protected: accessible in class + subclasses; private: only the exact declaring class.
- Partial<T>, Required<T>, Readonly<T>, Pick<T,K>, Record<K,T> are common built-in mapped utility types.
- Abstract classes cannot be instantiated but can be used as a type for instances of concrete subclasses.
- keyof T yields a union of a type's property names; T[K] is an indexed access type.
- Numeric enums exist at runtime with forward and reverse mappings; string literal unions do not.
- Overriding a method with an incompatible, non-optional signature breaks base-class substitutability.
4. Key Takeaways
- Access modifiers (public/protected/private) are enforced at compile time, not at runtime.
- Built-in utility types like Partial, Record, and Pick are built from mapped and conditional types.
- Generic constraints (T extends ...) restrict which types can be passed while preserving inference.
- Control-flow analysis narrows union types inside typeof/instanceof checks, including in ternaries.
- Exam questions often test whether you can trace a snippet to a precise inferred type or compiler error, not just define a term.
Practice what you learned
1. Which access modifier allows a member to be used by subclasses but not by external code?
2. What does `Partial<Point>` do to each property of Point?
3. Why does `function logLength<T extends { length: number }>(arg: T)` reject a plain number argument?
4. What does `keyof Point` evaluate to for `interface Point { x: number; y: number }`?
5. What are the runtime values of Direction.Up and Direction.Down in `enum Direction { Up, Down, Left, Right }`?
6. Why does overriding `greet(): void` with `greet(name: string): void` in a subclass cause a compile error?
7. What does `Record<'admin' | 'user', string[]>` produce?
8. In `[1, 2, 3].map(item => item * 2)`, how is the type of 'item' determined without an annotation?
9. What is the difference between a conditional type and a mapped type?
Was this page helpful?
You May Also Like
Common TypeScript Interview Questions
The most frequently asked TypeScript interview questions covering types, interfaces, generics, compilation, and tsconfig, with clear answers and code-tracing practice.
TypeScript vs JavaScript Interview Questions
Contrastive interview questions on why and how TypeScript extends JavaScript, covering compile-time vs runtime checking, structural typing, JS interop, and migration strategy.
Abstract Classes in TypeScript
Define shared structure and behavior for a family of subclasses using abstract classes and abstract methods that must be implemented by derived classes.
Utility Types in TypeScript
Learn TypeScript's built-in generic utility types — Partial, Required, Readonly, Pick, Omit, and Record — for transforming existing types.
Generic Constraints in TypeScript
Learn how to restrict generic type parameters with `extends` so generic code can safely rely on specific properties or shapes.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics