TYPESCRIPT INTERVIEWS
TypeScript interview questions
154 questions about TypeScript, the way interviewers ask them: 64 to explain, 45 where you predict what the compiler reports and infers, and 45 where you write the type or function. 52 easy, 71 medium, and 31 hard. Every answer is checked by the TypeScript compiler.
Every question is free to read. Sign in with Google to see the answers: the short version to say in the interview, why it's true, and what they'll ask next.
154 of 154 questions
Type basics
- What is type inference, and when should you still write type annotations?
- What types does TypeScript infer for these variables and this function?
- What are TypeScript's primitive types, and why write
stringrather thanString? - What's the difference between
anyandunknown? - What is a union type, and why can't you call
toUpperCase()on astring | number? - Type
label(size)so it only accepts"small","medium", or"large". - Why does
request(method)compile butrequest(other)doesn't? - What does TypeScript infer for these array literals?
- What's the difference between
{},object, andunknown? - What are the top and bottom types in TypeScript, and where does
anyfit? - With
noUncheckedIndexedAccesson, what are these types, what does TypeScript report, and what does it log? - Write
toArray(value): take one value or an array of values, and always return an array. - Which of these does TypeScript type as
never? - Write
LiteralUnion<T>: suggest some string literals in the editor, but still accept any string. - Write
compact(values): remove the falsy values, and type the result without the falsy types.
Objects & interfaces
- TypeScript is structurally typed. What does that mean?
- All three objects have an extra
adminproperty. Which lines does TypeScript reject? - What's the difference between
age?: numberandage: number | undefined? - What is an index signature, and when would you use
Recordinstead? - Write a
Profiletype with a read-onlyid, an optionalbio, and any number of named links. - What's the difference between an
interfaceand atypealias, and which should you use? - What does TypeScript report for these conflicting
extendsand&declarations? - Does
readonlystop these mutations? What does TypeScript report, and what does the code log? - Which of these arguments does TypeScript accept for an
objectparameter, and which for aRecord<string, unknown>parameter? - Which object literals does TypeScript reject when the target is a union?
- What is declaration merging, and when is it useful?
- Fix the type error in
countWords, and make it count every word correctly. - Why does
Object.keys(point)returnstring[]instead of(keyof Point)[]? - In an interface, what's the difference between
validate(value: string): booleanandvalidate: (value: string) => boolean? - Type a style object that allows
width,height,color, and any custom property starting with--.
Functions
- How do you type a function's parameters and return value, and when should you write the return type?
- What's the difference between
x?: number,x = 10, andx: number | undefinedas a parameter? - How do you write the type of a function, and when do you need a call signature instead of an arrow type?
- Which of these callback parameters does TypeScript infer, and which one is an error?
- Type
formatPrice(amount, currency, decimals)so onlyamountis required. - What's the difference between
voidandundefinedas a return type? What does TypeScript report here, and what does it log? - Why can you pass a callback with fewer parameters than its type declares, but not one with more?
- Why can you spread
pointintosumbut not intomove? - Write
createCounter(): a function you call to count, with acountproperty and areset()method. - How do you type
thisinside a function, and what does "'this' implicitly has type 'any'" mean? - What are function overloads, and when should you use a union parameter instead?
- Add overloads to
on(event, handler)so each event's handler gets the right parameter type. - Which of these calls to an overloaded function compile, and what is
ReturnType<typeof parse>? - Which detached method does TypeScript catch, and what does this log?
- Type
debounce(fn, wait)so the returned function takes exactly the same arguments asfn.
Narrowing & assertions
- What is narrowing in TypeScript, and which checks narrow a type?
- What does TypeScript narrow these
typeofand truthiness checks to, and what does the code log? - When do you narrow with
in, and when withinstanceof? - What is a discriminated union, and why is it better than an object with optional fields?
- What does
as constdo to these types, and what does the code log? - Write
isShape(value): a type guard for a discriminated union that arrives asunknown. - What's the difference between a type guard (
x is T) and an assertion function (asserts x is T)? - Which of these
filtercallbacks does TypeScript turn into a type predicate? - What's the difference between
as,satisfies, and a type annotation? - Which of these type assertions does TypeScript accept, and what types do they give?
- Make
area(shape)exhaustive, so adding a shape without handling it is a compile error. - Why doesn't
ROLES.includes(value)compile here, and how do you writeisRole(value)so it narrows? - Why does TypeScript forget a narrowing inside a callback?
- Which of these indirect checks does TypeScript still narrow on?
- Can a type predicate lie? What's wrong with this
isNonEmptyStringguard?
Generics
- Why use generics instead of
any? - What does TypeScript infer for
Tin each of these calls? - Make
createState(initial)generic, sogetandsetuse the type of the initial value. - What does
T extends …mean on a type parameter, and why do you need it? - How do you write a generic interface or type alias, and when do you have to pass its type argument?
- Which of these
getPropertycalls compile, and what does each return? - What are default type parameters, and when does TypeScript use the default?
- How do you write a generic class, and why can't its static members use the type parameter?
- Why is a type parameter that appears only once in a signature a code smell?
- Write
pick(obj, keys): return a new object with only the listed keys, typed to match. - Write a typed
groupBy(items, getKey)that groups items into an object by the key the callback returns. - What does the
constmodifier on a type parameter change in these calls? - What does
NoInfer<T>do, and when do you need it? - What happens when you pass only some of a generic function's type arguments?
- Write a typed event emitter:
onandemitshould only accept the events, and the arguments, of an event map. fetchJson<T>(url)compiles, but it lies aboutT. Rewrite it so the type is backed by a runtime check.
Type manipulation
- What do
keyofandtypeofdo in a type, and what doeskeyof typeof configgive you? - What do these indexed access types resolve to, and which lines does TypeScript reject?
- Write
TupleToUnion<T>, and use it to derive aRoleunion from arolesarray. - What is a conditional type, and how does
T extends U ? X : Ydecide? - What are template literal types, and what do
UppercaseandCapitalizedo? - What do these conditional types produce when you pass them a union?
- What does
inferdo in a conditional type? - Write
UnwrapPromise<T>: the value a promise resolves to, however deeply it's nested. - What is a mapped type, and what do
-readonly,-?, andasdo in one? - Write
Getters<T>: turn{ name: string }into{ getName: () => string }. - Write
KeysOfType<T, V>: the keys ofTwhose values are assignable toV. - Write
EventHandlers<T>: from an event map like{ click: Point }, build optionalonClick-style handler props. - What do these template literal types infer?
- How do you write a recursive type in TypeScript, and what are its limits?
- Write
PathKeys<T>: every dot path into a nested object, like"account.address.city".
Utility types
- What are utility types, and what do
Partial,Required, andReadonlydo? - When would you use
Pick, and whenOmit? - What does TypeScript report and infer for these
Recordtypes? - What do
Exclude,Extract, andNonNullableproduce for these types? - Write
MyPartial<T>without using the built-inPartial. - Write
MyPick<T, K>: keep only the keysKofT, and reject keysTdoesn't have. - Write
MyReadonly<T>, and its opposite,Mutable<T>, which removesreadonly. - What do
ReturnType,Parameters,Awaited, andInstanceTypegive for this code? - Type
updateUser(user, changes)sochangescan hold any editable field, but neveridorcreatedAt. - Is
Partial<User>a good type for a form's state? What can go wrong? - Write
MyOmit<T, K>without the built-inOmit, and make it reject keys thatTdoesn't have. - Write
MyReturnType<T>without the built-inReturnType. - Write
DeepPartial<T>for nested settings, keeping functions callable and arrays as arrays. - Write
DeepReadonly<T>: make every nested property and array readonly, but keep functions callable. - Write
MyAwaited<T>so it unwraps any thenable the wayawaitdoes, not only aPromise. - What happens when you
Omita key from a discriminated union?
Classes
- What do
public,private, andprotectedmean on a class member? - What's the difference between
implementsandextendson a class? - Which writes to these
readonlyproperties does TypeScript reject, and what does the code log? - What are parameter properties, and why does
erasableSyntaxOnlyreject them? - Make
balancereadable but not writable from outside the class. - Which of these properties does TypeScript say are never initialized?
- A class has a
privateproperty and a#privatefield. What does TypeScript report, and what does the code log? - When would you use an abstract class instead of an interface?
- With
noImplicitOverrideon, which lines in this subclass does TypeScript report? - Which of these values does TypeScript accept as class instances, and what does the code log?
- What's the difference between the types
Userandtypeof User? - Fix the builder so chained calls keep the subclass type.
- Type
instantiate(Ctor, ...args)so it accepts any class with matching arguments and returns its instance. - How are TypeScript 5's standard decorators different from
experimentalDecorators? - Why does
user.namelogundefinedhere, when the base constructor set it? - Type the
Taggedmixin so the class it returns keeps the base class's members and constructor.
Modules & configuration
- What does
import typedo, and how is it different from a regular import? - What is a
.d.tsfile, and where do the types for an npm package come from? - What does
strictturn on, and which flags would you add on top of it? - What's the difference between
target,lib, andmodulein a tsconfig? - How can TypeScript check a JavaScript file without converting it to TypeScript?
- Enums, union types, or
as constobjects: which would you use, and why? - Replace this
Sizeenum with anas constobject, and add anisSizeguard for strings that come from outside. - With
verbatimModuleSyntaxon, which of these imports and exports does TypeScript reject? tiny-slugships no types. Write a declaration soimport { slugify } from "tiny-slug"is fully typed.- This file should add
analyticstowindow, but TypeScript rejects it. Fix it, and declare a global__APP_VERSION__too. - Vite, esbuild, and Node.js run TypeScript without checking it. So what catches the type errors?
- With
erasableSyntaxOnlyon, which of these lines does TypeScript reject? - This
.d.tsfile was meant to addbrandColorto shop-ui'sTheme. What does TypeScript report inapp.ts? - Under
module: nodenext, which of these imports does TypeScript reject, and why write.jsfor a.tsfile? - Type checking a large repo has become slow. What do
skipLibCheck,incremental, and project references do about it?
TypeScript in practice
- What types do these DOM queries return, and what does TypeScript report?
- In these event listeners, why is
event.target.valuean error, and what type isevent? - Why is
await response.json() as Userunsafe, and what should you do instead? - Write
isUser(value): a type guard that checks parsed JSON really is aUser. - Why is the
catchvariableunknownin TypeScript, and how do you handle errors safely? - How do you type a React component's props,
children, and event handlers? - What types does TypeScript give this async code, and which line is an error?
- Write a
Result<T, E>type andattempt(fn), which returns errors as values instead of throwing them. - How do you type
useState,useReducer, anduseRefin React? - Write branded
UserIdandProductIdtypes, so one can't be passed where the other is expected. - How would you migrate a large JavaScript codebase to TypeScript without stopping feature work?
- How do you read a long TypeScript error message, like the one this call gives?
- What TypeScript habits do you follow on a real project?
- Which of these event handler assignments does TypeScript reject, and why does the method version compile?
- This compiles with no errors. What does it log, and where does TypeScript's type safety break down?
- Write a type-safe API client from a route map: each route takes the right body and resolves to the right response type.