PrepStack › Frontend › TypeScript
TypeScript interview cheat sheet
Type system, narrowing, generics, type-level tricks and typing React
TypeScript rounds test whether you can model data with types rather than just add : string everywhere. Expect questions on any vs unknown, interface vs type, narrowing and discriminated unions, generics with constraints, utility types (often “implement Pick yourself”), conditional types with infer, satisfies, tsconfig strictness and typing React components. Read the 15-minute revision first, then use Quiz mode. The snippets use @ts-expect-error to prove which lines fail to compile.
15-minute revision
- TypeScript is a compile-time layer over JavaScript. Types are erased, so they never change runtime behaviour or exist at runtime.
- Typing is structural: if the shape fits, it is assignable. Names do not matter. Fresh object literals also get an excess property check.
anyturns checking off.unknownis the safe top type: you must narrow it before use.neveris the empty type (impossible values, exhaustive checks).voidmeans “return value is ignored”.interfacecan be merged and extended;typecan alias anything (unions, tuples, mapped and conditional types). For object shapes either works.- Narrowing tools:
typeof,instanceof,in, equality, truthiness, discriminated unions (a shared literalkindfield),x is Tpredicates andasserts x is Tfunctions. - Exhaustive check: in the
defaultbranch assign the value tonever. Adding a new union member then becomes a compile error. - Generics are type parameters. Constrain them with
extends(K extends keyof T). ReturnT[K]for typed property access. keyof Tgives a union of keys,typeof xlifts a value into a type,T[K]is an indexed access type.(typeof arr)[number]gives the element type.- Utility types are just mapped/conditional types:
Partial,Required,Readonly,Pick,Omit,Record,Exclude,Extract,NonNullable,ReturnType,Parameters,Awaited. - Conditional types distribute over unions when the checked type is a naked type parameter. Wrap in
[T]to stop it.infercaptures a part of a matched type. - Prefer
as constobjects or string-literal unions over enums. Numeric enums are reverse-mapped and loosely typed;const enumbreaks with isolated per-file transpilers. satisfieschecks a value against a type without widening it. An annotation (: T) replaces the inferred type withT.privateis compile-time only;#fieldis real JS privacy.abstractclasses cannot be instantiated. Parameter properties (constructor(public x: number)) declare and assign in one go.strict: trueenablesstrictNullChecks,noImplicitAny,strictFunctionTypesand more. AddnoUncheckedIndexedAccessfor safer arrays. In TS 6.0+strictis on by default.- TypeScript 7 (July 2026) is a native Go port of the compiler, roughly 10x faster, with the same type system. TS 6.0 was the bridge release that deprecated old options.
- React: type props with an interface,
children: React.ReactNode, events asReact.ChangeEvent<HTMLInputElement>,useState<User | null>(null),useRef<HTMLDivElement>(null).
Foundations
Why TypeScript & structural typing
TypeScript adds a static type checker on top of JavaScript; it compares shapes, not names, and erases every type at build time.
- TypeScript is a superset of JavaScript: valid JS is (mostly) valid TS. The compiler checks types and then emits plain JS with the types removed.
- Benefits: bugs caught before running, safe refactors, editor autocomplete and go-to-definition, and types that act as up-to-date documentation.
- Structural typing (duck typing at compile time): a value fits a type if it has the required properties with compatible types. A class instance and a plain object with the same shape are interchangeable.
- Excess property check: a fresh object literal passed straight to a typed slot cannot have unknown properties. The same object through a variable is allowed. It catches typos.
- Type erasure: no types exist at runtime, so you cannot do
if (x is User)at runtime. You need real JS checks (typeof,in, schema validation) for external data. - The type system is intentionally not fully sound (e.g. array covariance,
any, type assertions). It trades soundness for practicality.
Interview questions
- What is TypeScript and why use it?
- What does “structural typing” mean?
- Why is
{ x: 1, y: 1, label: 'b' }an error but the same object in a variable is fine? - Does TypeScript make your app type-safe at runtime?
Primitives, any, unknown, never & void
unknown is the safe version of any; never means “cannot happen”; void means “ignore the return value”.
- Primitive types:
string,number,bigint,boolean,symbol,null,undefined. Use lower case;String/Numberare wrapper object types. anydisables type checking for a value and spreads: anything you read from it is alsoany. Treat it as an escape hatch.unknownaccepts any value, but you cannot use it until you narrow it. Use it forJSON.parseresults,catchvariables and untrusted input.neverhas no values. It is the return type of functions that always throw or loop forever, the result of impossible intersections (string & number) and the tool for exhaustive checks.voidis the return type of functions whose result should be ignored. At runtime they returnundefined.- With
strictNullChecks,nullandundefinedare separate types.stringno longer includes them, so you must writestring | null.
Interview questions
- Difference between
anyandunknown? - What is
neverand where is it used? - Difference between
voidandundefinedas a return type? - What does
strictNullCheckschange?
interface vs type alias
Both describe object shapes; interface merges and extends, type can name any type expression.
interfacedescribes object shapes (and classes, functions). It supportsextendsand declaration merging: twointerface Userblocks become one.typegives a name to any type: unions, tuples, primitives, function types, mapped and conditional types.- Extending:
interface B extends A {}vstype B = A & {}. Conflicting members inextendsare a clear error; in an intersection they silently becomenever. - Declaration merging is how libraries let you augment global types such as
WindoworExpress.Request. - Many teams use
interfacefor public object shapes andtypefor unions and computed types. Pick one rule and be consistent.
Interview questions
- Difference between
interfaceandtype? - What is declaration merging?
- What happens when an intersection has conflicting property types?
Unions, intersections & literal types
A | B is “either”, A & B is “both”; literal types like 'GET' restrict a value to exact strings or numbers.
- A union
string | numberaccepts either. You can only use members that exist on every branch until you narrow. - An intersection
A & Bmust satisfy both. It is used to combine object types or add fields (T & { id: string }). - Literal types:
'GET',42,true. A union of literals ('sm' | 'md' | 'lg') is the idiomatic replacement for many enums. - Widening:
let m = 'GET'isstring;const m = 'GET'is'GET'. Object properties widen too, because they can be reassigned. as constmakes literals readonly and keeps their literal types, for objects and arrays (tuples).- Tuples are fixed-length arrays with per-position types:
[string, number], optional[string, number?]and labelled[name: string, age: number].
Interview questions
- Difference between a union and an intersection type?
- What is type widening?
- What does
as constdo?
Narrowing & functions
Narrowing & discriminated unions
Control-flow analysis narrows a union inside each branch based on runtime checks you write.
typeofnarrows primitives ('string','number','object','function'...). Remembertypeof null === 'object'.instanceofnarrows to a class;'key' in objnarrows to union members that have that key.- Equality (
=== null,=== 'circle') and truthiness (if (x)) narrow too. Truthiness also drops0and'', which may be a bug. - Discriminated (tagged) union: every member has a common literal field like
kind. Switching on it narrows to the exact member. - Exhaustiveness: in
default, assign the value to anevervariable. If someone adds a member, that line stops compiling. - Narrowing is reset by assignments and does not survive into callbacks for
letvariables. Copy to aconstfirst.
Interview questions
- What is type narrowing?
- What is a discriminated union and why is it useful?
- How do you make a
switchexhaustive? - Why might narrowing be lost inside a callback?
Custom type guards & assertion functions
x is T predicates narrow in an if; asserts x is T functions narrow everything after the call or throw.
- A type predicate
function isCat(x: unknown): x is Catreturns boolean, and when true the caller's variable is narrowed toCat. - The compiler trusts your predicate. If the body is wrong, the types lie. Keep guards small and tested.
- An assertion function
asserts v is stringthrows when the check fails. After the call,vis narrowed for the rest of the scope. asserts cond(no type) narrows based on a boolean condition, like Node'sassert.- Since TS 5.5, simple predicates are inferred:
arr.filter(x => x !== null)returnsT[]withoutnull. - Assertion functions must be called through an explicitly typed reference (a function declaration or an annotated
const).
Interview questions
- What is a user-defined type guard?
- Difference between a type guard and an assertion function?
- Is a type predicate checked by the compiler?
Function types & overloads
Type parameters and return values, use optional/default/rest params, and add overload signatures when the return type depends on the arguments.
- Function type syntax:
(a: number, b: number) => number. Object form with a call signature:{ (a: number): number; label: string }. - Optional params
b?: number, defaultsb = 1(type inferred) and rest...xs: number[]. Optional params come last. - A function with fewer parameters is assignable to a type with more. That is why
arr.forEach(x => ...)works withoutindexandarray. - Overloads: several signatures followed by one implementation. Callers only see the overload signatures, not the implementation signature.
- Prefer a union parameter or a generic over overloads when the return type does not change with the input.
- Declare a
thisparameter (function f(this: Window)) to typethis; it is erased in the output.
Interview questions
- What are function overloads and when would you use them?
- Why can you pass a 1-parameter callback where a 3-parameter one is expected?
- What is the difference between
?optional and| undefined?
Generics & constraints
Generics are type parameters that keep the link between inputs and outputs; extends limits what callers can pass.
- A generic function
first<T>(xs: T[]): Tworks for anyTwhile preserving the exact type. Callers rarely passT; it is inferred. - Constraints:
T extends { length: number }lets you use.lengthinside.K extends keyof Tlimits a key to real keys ofT. - Defaults:
interface ApiResponse<D = unknown>. Generic classes and interfaces work the same way. - const type parameters (TS 5.0):
function f<const T>(x: T)infers literal/tuple types as if the caller wroteas const. NoInfer<T>(TS 5.4) stops a parameter from being used as an inference source, e.g. adefaultValuethat must match the list.- Do not add a generic that appears only once.
function log<T>(x: T): voidis just(x: unknown) => void.
Interview questions
- What are generics and why use them instead of
any? - What does
K extends keyof Tmean? - What are
consttype parameters? - When should you not use a generic?
keyof, typeof & indexed access types
typeof turns a value into a type, keyof gives its keys, and T[K] reads a property type.
typeof configin a type position gives the inferred type of a value. It lets one runtime object be the single source of truth.keyof Tis the union ofT's property names. For an index signature{ [k: string]: X }it isstring | number.- Indexed access
T['port'],T[keyof T](union of all value types) andArr[number](element type). (typeof ROLES)[number]withROLES = [...] as constgives a union of the literal values.Object.keys(obj)returnsstring[], not(keyof T)[], because objects may have extra keys at runtime (structural typing).
Interview questions
- Difference between
typeofin JavaScript and in a TypeScript type? - Why does
Object.keysreturnstring[]and not(keyof T)[]? - How do you derive a union type from an array of strings?
Type-level programming
Utility types & how they are built
Built-in helpers like Partial, Pick, Omit and ReturnType are a few lines of mapped and conditional types; be ready to write them.
- Shape modifiers:
Partial<T>,Required<T>,Readonly<T>. They change modifiers on every property (shallowly). - Selecting:
Pick<T, K>keeps keys,Omit<T, K>removes keys,Record<K, V>builds an object type from a key union. - Union filters:
Exclude<U, X>removes members,Extract<U, X>keeps them,NonNullable<T>dropsnull/undefined. - Function helpers:
ReturnType<F>,Parameters<F>,ConstructorParameters<C>,InstanceType<C>. Awaited<T>unwraps promises recursively, the wayawaitdoes.ReturnType<typeof fetchUser>+Awaitedgives the resolved data type.- Others:
NoInfer<T>,ThisType<T>, and string helpersUppercase,Lowercase,Capitalize,Uncapitalize.
Interview questions
- Implement
PickandOmit. - Difference between
Pick/OmitandExtract/Exclude? - How do you get the resolved type of an async function's result?
- Is
Partial<T>deep?
Mapped types & key remapping
{ [K in Keys]: ... } loops over a key union to build a new object type, with control over modifiers and key names.
{ [K in keyof T]: T[K] }copiesT. Change the right side to transform values, e.g.T[K] | null.- Modifiers: add or remove
readonlyand?with+/-:-readonlymakes a type mutable,-?makes properties required. - Mapped types over
keyof Tare homomorphic: they keep the original optional/readonly modifiers. - Key remapping with
as(TS 4.1):[K in keyof T as NewKey]. Map a key toneverto filter it out. - Combine with template literal types to generate names like
getName,onChange,setValue.
Interview questions
- What is a mapped type?
- How do you remove
readonlyor?from all properties? - How do you filter properties by their value type?
Conditional types & infer
T extends U ? X : Y is an if/else for types; it distributes over unions and can capture parts with infer.
T extends U ? X : Ychecks assignability at the type level. It is evaluated whenTis known, so generic results stay deferred until then.- Distribution: if
Tis a naked type parameter and you pass a union, the condition runs per member and the results are unioned. - Stop distribution by wrapping both sides in a tuple:
[T] extends [U]. Needed for checks likeIsNever<T>. neveris an empty union, so a distributive conditional overneverreturnsnever.infer Xdeclares a type variable inside theextendsclause to capture part of the matched type (element, return, promise value).- Conditional types can be recursive (
DeepReadonly,Awaited, string parsers). The compiler has depth limits, so keep recursion shallow.
Interview questions
- What is a conditional type?
- What are distributive conditional types?
- What does
inferdo? - Why does
IsNever<never>written asT extends never ? true : falsereturnnever?
Template literal types
Backtick types build and parse string literal types, e.g. event names, CSS units and route params.
- Written with backticks at the type level: a template like
on${Capitalize<Name>}builds new string literal types from other literals. - Interpolating unions produces the cross product: 2 sizes × 2 colors = 4 variant names.
- Intrinsic helpers:
Uppercase,Lowercase,Capitalize,Uncapitalize. - With
inferyou can parse strings: extract route params from'/users/:id'or split on a dot. - Pattern types: the template
/${string}accepts any string that starts with a slash, and${number}pxaccepts '12px'.
Interview questions
- What are template literal types?
- How would you type route params from a path string?
Language features
Enums vs literal unions & as const
Enums create real runtime objects; most teams now prefer string-literal unions or as const objects.
- Numeric enums auto-increment from 0 and get a reverse mapping (
Direction[0] === 'Up'), soObject.keysshows both numbers and names. - String enums have no reverse mapping and are nominal: you cannot pass the raw string
'ACTIVE'whereStatusis expected. const enumis inlined at compile time and leaves no object, but breaks underisolatedModulesand single-file transpilers across files.- Enums are one of the few TS features with runtime output, so Node's type stripping and
erasableSyntaxOnly(TS 5.8) reject them. - Alternative: an
as constobject for runtime values plus a derived union type. It is plain JS, tree-shakes well and accepts raw strings.
Interview questions
- Enum vs union of string literals: which do you prefer?
- What is a reverse mapping?
- What is a
const enumand what is the catch?
satisfies, assertions & non-null
satisfies validates without changing the inferred type; as overrides the checker; ! removes null without checking.
- An annotation
const x: T = ...sets the variable's type toT. You lose more specific information from the value. value satisfies T(TS 4.9) checks the value againstT, including excess properties, but keeps the inferred type.- Combine
as const satisfies Tto get literal readonly types plus validation, great for config and route maps. - A type assertion
x as Ttells the compiler to trust you. It only allows assertions between related types;as unknown as Tforces anything. - The non-null assertion
x!removesnull | undefined. It does nothing at runtime, so a wrong!crashes later. - Prefer narrowing over assertions. Use
asmainly at boundaries (e.g.document.getElementById('x') as HTMLInputElement).
Interview questions
- What does
satisfiesdo and how is it different from a type annotation? - Difference between
asandsatisfies? - What is the non-null assertion operator?
Classes, access modifiers & abstract
TS adds public/private/protected, readonly, parameter properties, abstract and implements on top of JS classes.
public(default),protected(class + subclasses),private(class only). These are compile-time checks only.#fieldis a JS private field: enforced at runtime, invisible toObject.keysandJSON.stringify.- Parameter properties:
constructor(private readonly id: string)declares and assigns the field in one step. abstract classcannot be instantiated;abstractmethods must be implemented by subclasses. It can also hold shared code.implements Interfaceonly checks the class shape; it does not add any code or inherit anything.overridekeyword (withnoImplicitOverride) catches methods that no longer override anything after a base class rename.
Interview questions
- Difference between
privateand#private? - Difference between an abstract class and an interface?
- What are parameter properties?
Project setup
Modules & declaration files
.d.ts files describe the types of JavaScript code; declare adds types without emitting code; augmentation extends existing types.
- A file with a top-level
import/exportis a module; otherwise it is a global script whose declarations leak into the global scope. .d.tsfiles hold only types. Libraries ship them ("types"in package.json) or you get them from DefinitelyTyped (@types/react).declaredescribes something that exists at runtime but was not written in TS:declare const VERSION: string,declare module 'legacy-lib'.declare module '*.svg'types non-JS imports for bundlers. Module augmentation adds members to an existing module's interfaces.declare global { interface Window { ... } }inside a module augments globals.import type/export typeare erased completely; required withverbatimModuleSyntaxso transpilers know what to drop.
Interview questions
- What is a
.d.tsfile? - What does the
declarekeyword do? - How do you add a property to the global
Windowor a library type? - What is the difference between
import typeand a normal import?
tsconfig & strict mode
strict: true turns on the important safety checks; a few extra flags catch even more, and TS 6/7 changed several defaults.
strictis a bundle:strictNullChecks,noImplicitAny,strictFunctionTypes,strictBindCallApply,strictPropertyInitialization,noImplicitThis,alwaysStrict,useUnknownInCatchVariables,strictBuiltinIteratorReturn.- Popular extras:
noUncheckedIndexedAccess(index reads includeundefined),exactOptionalPropertyTypes,noImplicitOverride,noFallthroughCasesInSwitch. targetsets the JS syntax output;libsets which built-in APIs are typed (DOM,ES2023);module+moduleResolutiondecide how imports are resolved (bundler,nodenext).- For bundler apps:
noEmit: true,moduleResolution: "bundler",isolatedModules/verbatimModuleSyntax,jsx: "react-jsx". skipLibCheckskips checking.d.tsfiles in dependencies to speed up builds.- TS 6.0 made
strictdefault totrue,moduledefault toesnext,typesdefault to[], and deprecatedtarget: es5,baseUrlandmoduleResolution: node. TS 7.0 removed those deprecated options.
Interview questions
- What does
strict: trueenable? - What does
noUncheckedIndexedAccessdo and why is it not instrict? - Difference between
targetandlib? - What changed in TypeScript 6 and 7?
React & puzzles
Typing React components & hooks
Type props with an interface, let hooks infer where they can, and give explicit generics for useState unions, refs, reducers and context.
- Props: a plain function
function Button({ label }: ButtonProps).React.FCis optional and no longer adds implicitchildren(React 18 types). children: React.ReactNodeaccepts anything renderable.React.ReactElementis narrower (only JSX elements).- Events:
React.ChangeEvent<HTMLInputElement>,React.MouseEvent<HTMLButtonElement>,React.FormEvent<HTMLFormElement>. Inline handlers infer it for you. useState<User | null>(null)needs the generic becausenullalone would infernull.useRef<HTMLInputElement>(null)for DOM refs.- Extend native props:
React.ComponentProps<'button'>orReact.ButtonHTMLAttributes<HTMLButtonElement>, thenOmitwhat you override. - Generic components (
function List<T>(props: ListProps<T>)) keep item types flowing intorenderItem. Reducers work best with a discriminated-unionActiontype.
Interview questions
- How do you type a component's
children? - Should you use
React.FC? - How do you type
useStatewhen the initial value isnull? - How do you build a component that accepts all native button props plus your own?
- How do you write a generic
Listcomponent?
Output & compile-error puzzles
Most TypeScript trick questions come from erasure, unsound spots and inference rules.
- Array covariance:
Dog[]is assignable toAnimal[], so you can push a cat into a dog array through the wider reference. - Index access on arrays and records is typed as the element type, even if the item does not exist (unless
noUncheckedIndexedAccess). - Assertions do not convert:
'42' as unknown as numberis still a string, so+ 1concatenates. - Optional property
x?: numbermay be missing entirely;'x' in ois false. - Excess property checks only apply to fresh literals. readonly and private vanish at runtime.
Object.keysreturnsstring[], so indexing a typed object with its result fails to compile.
Interview questions
- Is TypeScript's type system sound? Give an example.
- What prints:
const n = '42' as unknown as number; console.log(n + 1)? - Why does
p[k]fail insidefor (const k of Object.keys(p))? - If
readonlypreventspush, why can the array still change?