TypeScript Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is TypeScript?
Correct answer: A superset of JavaScript with static typing that compiles to JS
Any valid JS is almost always valid TS. Types are checked at compile time and then erased: plain JavaScript runs at runtime, and there are no type checks there. That's why external data (APIs, forms) is still validated at runtime - e.g. with Zod.
2. Does TypeScript check types while the program is running?
Correct answer: No: types are erased at compile time; plain JS runs at runtime
TypeScript is a development-time tool. If an API returns
nullinstead of an object, types won't save you. For runtime checks, usetypeof/instanceofand schema libraries (Zod, Valibot), from which you can also infer TS types.3. How does
unknowndiffer fromany?Correct answer: You can't do anything with
unknownwithout narrowing, whileanydisables checksanyturns typing off and "infects" everything it touches.unknownis the safe counterpart: the value can be anything, but you can use it only after a check (typeof x === 'string'). For data fromJSON.parseandcatch (e),unknownis the right choice.4. What does the
nevertype mean?Correct answer: The type of a value that can't exist: the function never returns control
neveris the empty type. It's returned by functions that always throw or loop forever. It also appears when a union is fully narrowed - exhaustiveswitchchecks are built on this.voidmeans the function finishes but its result isn't used.5. What type does TypeScript infer for
let x = 5;?Correct answer:
numberType inference: for
let, the literal widens tonumberbecause the variable can be reassigned. Forconst x = 5, the type is the literal5. Explicit annotations are needed where inference is impossible or imprecise - e.g. in function parameters.6. What's the difference between
interfaceandtypefor describing an object?Correct answer: Both work;
interfacecan be extended by merging, whiletypecan express unions and moreFor objects they're almost interchangeable. Differences: interfaces with the same name merge (declaration merging) and are extended with
extends. Type aliases describe unions, tuples, primitives, conditional and mapped types. Many teams useinterfacefor objects andtypefor everything else.7. How do you declare an optional object property?
Correct answer:
{ name?: string }A
?after the name makes the property optional: its type isstring | undefined, and the key itself may be missing. With theexactOptionalPropertyTypesflag, explicitly assigningundefinedis distinguished from a missing key.8. What does the
readonlymodifier do in{ readonly id: number }?Correct answer: Forbids reassigning the property at the type level; nothing changes at runtime
readonlyis just a compiler check:obj.id = 2causes an error. It's shallow - nested objects can be changed. At runtime the object is ordinary. For arrays there'sreadonly string[]/ReadonlyArray<string>, and deep freezing is done withas constorObject.freeze.9. What does the type
string | numbermean?Correct answer: The value can be a string or a number (a union)
A union type allows any of its members. Until the type is narrowed, only operations common to all members are available. An intersection is written with
&and requires matching all types at once (A & B).10. What does the intersection
type Admin = User & { role: 'admin' }give you?Correct answer: A type with all the properties of
Userplusrole: 'admin'An intersection combines requirements: the value must satisfy both types. It's a way to compose types, similar to
interface Admin extends User. Conflicting properties produceneverfor that property.11. What is the literal type
'left' | 'right'?Correct answer: Only the strings
'left'or'right'Literal types narrow a value down to specific constants. A union of literals is a common alternative to enums:
type Direction = 'left' | 'right'. The compiler catches the typo'lft', and the IDE suggests the options.12. How do you type a function that takes a string and returns a number?
Correct answer:
(s: string) => numberIn a function type, parameter names are required:
(s: string) => number.(string) => numbermeans a parameter namedstringof typeany. A function declaration:function len(s: string): number { ... }.13. How do you declare an optional function parameter?
Correct answer:
function greet(name?: string)?makes the parameter optional; its type isstring | undefined. The alternative is a default value:greet(name = 'Guest'), in which case the type is inferred asstring. Optional parameters must come after required ones.14. What is a tuple in TypeScript?
Correct answer: A fixed-length array with a known type for each element
type Point = [number, number]- exactly two numbers. Tuples are handy for returning several values, as inuseState:[value, setter]. Elements can be named ([x: number, y: number]) and made optional ([string, number?]).15. How do you type an array of strings?
Correct answer:
string[]orArray<string>string[]andArray<string>are equivalent.[string]is a one-element tuple. For read-only arrays usereadonly string[].16. What is a generic?
Correct answer: A type parameter that keeps the link between types in reusable code
function first<T>(arr: T[]): T | undefined- the result type is linked to the input array's type:first([1, 2])returnsnumber | undefined. Withany, that link is lost. Generics are used inArray<T>,Promise<T>,useState<T>.17. What does the utility type
Partial<User>do?Correct answer: Makes all properties of
UseroptionalPartial<T>adds?to every property - handy for update objects:update(id, patch: Partial<User>). Selecting a subset isPick, read-only isReadonly, all required isRequired.18. How do
Pick<User, 'id' | 'name'>andOmit<User, 'password'>differ?Correct answer:
Pickkeeps the listed properties,Omitkeeps everything except themBoth create a new type from an existing one.
Pickis an allowlist of keys,Omita denylist. For example,Omit<User, 'password'>is a type for an API response without secret fields.19. What does
Record<string, number>describe?Correct answer: An object whose keys are strings and values are numbers
Record<K, V>is an object with keysKand valuesV. With union keys it requires all of them:Record<'en' | 'uk', string>. It isn't aMap:Mapis a separate data structure withget/setmethods.20. What does
keyof { id: number; name: string }return?Correct answer:
'id' | 'name'keyofreturns a union of a type's keys. Value types are obtained via indexed access:T['id']orT[keyof T].keyofdoesn't exist at runtime - useObject.keysfor an array of keys.21. What does
typeofdo in a type position:type Config = typeof config?Correct answer: Takes the compiler-inferred type of the
configvariableIn expressions,
typeofis the JS operator that returns a string. In a type position, it's a TypeScript operator that extracts a value's type. Handy for avoiding duplication:const routes = {...} as const; type Routes = typeof routes.22. What's wrong with
function greet({ name: string }) {}?Correct answer: It renames
nameto a variablestring, the type isn't setIn destructuring, a colon means renaming, not a type: the code creates a variable
string, and the parameter stays without a type (understrictit's an implicitanyerror). The type goes after the whole pattern:function greet({ name }: { name: string })or viatype Params = { name: string }.23. What is the type of
e.targetininput.addEventListener('input', (e) => ...)?Correct answer:
EventTarget | null- it has novalueeis inferred asEvent, and itstargetis a generalEventTarget | null: the event may come from a nested element. To readvalue, narrow it withif (e.target instanceof HTMLInputElement)or use theinputvariable itself, whose type is already known.24. What type does
const cache = new Map()get without type arguments?Correct answer:
Map<any, any>- better writenew Map<string, User>()With no arguments there is nothing to infer from, so
KandVbecomeanyand everyget/setgoes unchecked. Pass the types explicitly,new Map<string, User>(), or initial entries:new Map([['a', 1]])givesMap<string, number>.25. What does the type assertion
value as stringdo?Correct answer: Tells the compiler to treat the value as a string, with no runtime check
asis a hint to the compiler, not a conversion: if it's actually a number, the error shows up later. Use it when you know more than the compiler (e.g. the element type fromquerySelector), and prefer narrowing via checks.26. What does the
!operator do inuser!.name?Correct answer: Asserts the value isn't
null/undefined, with no runtime checkA non-null assertion removes
null | undefinedfrom the type. If the value isnullafter all, you get a runtime error. Safer options are an explicit check oruser?.name(optional chaining, returnsundefined).27. What does the
strictflag intsconfig.jsonenable?Correct answer: A set of strict checks:
strictNullChecks,noImplicitAnyand othersstrict: trueenables a family of flags:strictNullChecks,noImplicitAny,strictFunctionTypes,strictBindCallApply,useUnknownInCatchVariablesand others. New projects should start with strict. It doesn't forbid explicitany- there are linter rules for that.28. What does
strictNullChecksgive you?Correct answer:
nullandundefinedbecome separate types that must be handled explicitlyWithout the flag,
nullcan be assigned to anything, and "cannot read property of null" errors aren't caught. With it,stringdoesn't includenull: you writestring | nulland check the value before use. It's one of the most useful flags.29. How do you narrow
string | numbertostringinside a condition?Correct answer:
if (typeof value === 'string') { ... }TypeScript analyzes control flow: after a
typeofcheck, the type inside the branch is narrowed tostring, and inelsetonumber.instanceof Stringchecks for a wrapper object, not a primitive. Thex is Tsyntax is used in the signature of type guard functions.30. How does
enum Color { Red, Green }differ fromtype Color = 'red' | 'green'?Correct answer: An
enumcreates an object at runtime; a literal union exists only in typesA regular
enumcompiles to a JS object (a numeric one with reverse mapping). A string union adds nothing to the bundle and is compatible with JSON and APIs. Many teams prefer unions or anas constobject. Also, enums are incompatible witherasableSyntaxOnlymode.31. What does
as constdo inconst roles = ['admin', 'user'] as const?Correct answer: Makes the array a readonly tuple with the literal types
'admin'and'user'Without
as const, the type isstring[]. With it, it'sreadonly ['admin', 'user'], and you can derive a union:type Role = typeof roles[number]→'admin' | 'user'. The object isn't frozen at runtime.32. What is structural typing in TypeScript?
Correct answer: Type compatibility is determined by shape (the set of properties), not by name
If an object has all the properties a type requires, it fits - even if its type has a different name (duck typing). That's why
Point2DandVector2Dwith the same fields are interchangeable. Nominal behavior can be emulated with branded types.33. What is a
.d.tsfile?Correct answer: A declaration file: types for existing JS, no implementation
Declarations let you use JS libraries with types. They're written by hand, generated by the compiler (
declaration: true) or installed from DefinitelyTyped. A.d.tsfile contains no executable code.34. Why install packages like
@types/lodash?Correct answer: To get types for a library written in JS without built-in declarations
@types/*packages are published from the DefinitelyTyped repository and contain only.d.tsfiles. Many modern libraries ship their own types - then@typesisn't needed. They're usually installed as devDependencies.35. What does
tsccompile a TypeScript file into?Correct answer: JavaScript with the type annotations removed
The compiler checks types and outputs JS for the specified
target. In modern projects, building is often done by esbuild, SWC or Babel (which only strip types), andtsc --noEmitis run separately for checking.36. What is the type of
eincatch (e)withstrictenabled?Correct answer:
unknownWith the
useUnknownInCatchVariablesflag (part of strict),eisunknown, since anything can be thrown, not just anError. Check before use:if (e instanceof Error) console.log(e.message).37. What does the return type
voidmean?Correct answer: The function returns nothing useful; the result isn't used
voidis used for functions without areturnvalue. Caveat: the callback type() => voidallows passing a function that returns something (the result is ignored) - that's whyarr.forEach(x => list.push(x))compiles. A function that never finishes has the typenever.38. How do you describe an object with arbitrary string keys and number values using an index signature?
Correct answer:
{ [key: string]: number }An index signature describes a "dictionary". The equivalent is
Record<string, number>. With thenoUncheckedIndexedAccessflag,obj[key]returnsnumber | undefined, which better reflects reality.39. How do you extend an interface?
Correct answer:
interface Admin extends User { role: string }An interface is extended with
extends(from several at once:extends A, B).implementsis used by classes to guarantee they match an interface. For type aliases, the counterpart is an intersectionUser & { role: string }.40. What does
implementsdo in a class?Correct answer: Checks that the class matches the interface; it doesn't inherit anything
class Cat implements Animal- the compiler checks that the class has all the members ofAnimal. You have to write the implementation yourself, unlikeextendsfor classes. Interfaces don't exist at runtime.41. How does
privatein TypeScript differ from#fieldin JavaScript?Correct answer:
privateis only a compiler check,#fieldis privacy at runtimeAfter compilation, a
privatefield is an ordinary property that can be read viaobj['field'].#fieldprivate fields are supported by the JS engine and can't be accessed from outside the class at all. Thepublic,protectedandprivatemodifiers are TypeScript tools.42. How do you type an async function that returns a user?
Correct answer:
async function getUser(): Promise<User>An async function always returns a promise, so the result type is
Promise<User>. The annotationUsercauses an error. You can extract the promise's value type withAwaited<ReturnType<typeof getUser>>.43. What does TypeScript do with
const el = document.getElementById('app')?Correct answer: Infers
HTMLElement | nulland requires anullcheckThe element may not exist, so the type includes
null. For a specific type, usequerySelector<HTMLInputElement>('#email')or aninstanceof HTMLInputElementcheck. DOM types are part of the standard library (lib: ['dom']).44. What is a union with a common discriminant field?
type Shape = | { kind: 'circle'; radius: number } | { kind: 'square'; size: number };Correct answer: A discriminated union: TS narrows it by
kindThe check
if (shape.kind === 'circle')narrows the type, andshape.radiusis available inside. It's the main way to model states:{ status: 'loading' } | { status: 'success'; data } | { status: 'error'; error }.45. How do you get the return type of the
createStorefunction?Correct answer:
ReturnType<typeof createStore>ReturnTypetakes a function type, sotypeofis needed. Similarly,Parameters<typeof fn>gives a tuple of parameters. This way types are derived from the implementation instead of being duplicated.46. What happens when you pass an object literal with an extra property?
type User = { name: string }; const u: User = { name: 'Ann', age: 30 };Correct answer: An error: literals are subject to excess property checks
The excess property check applies only to fresh object literals - it's protection against typos. If you first put the object into a variable and then assign it, there's no error (structural compatibility). The compiler doesn't remove anything.
47. What is
tsconfig.json?Correct answer: A file with compiler settings and the list of project files
In
compilerOptionsyou settarget,module,strict,pathsand so on, whileinclude/excludedefine which files belong to the project. Dependencies are described bypackage.json, and types by.d.tsfiles. Configs can be inherited viaextends.48. How do you gradually migrate a JS project to TypeScript?
Correct answer: Enable
allowJs, rename files one by one and tighten the checksallowJslets you mix JS and TS, whilecheckJsand JSDoc give you types without renaming. Start with leaf modules and utilities, then tighten thestrictflags. A full rewrite is risky and halts development.49. How does
Required<T>differ fromPartial<T>?Correct answer:
Requiredmakes all properties required,Partialmakes them optionalThey're opposites:
Requiredremoves the?modifier,Partialadds it.readonlyis handled byReadonly<T>. All these utilities are mapped types that you can write yourself.50. How do you specify that a function accepts any number of numbers?
Correct answer:
function sum(...nums: number[])A rest parameter collects the arguments into an array; its type is an array or a tuple. Call it as
sum(1, 2, 3)orsum(...arr).51. What does the
noImplicitAnyoption report?function greet(name) { return 'Hi ' + name; }Correct answer: Values whose type silently falls back to
anyHere
namewould beany. The flag is part ofstrict. Writinganyexplicitly is still allowed, but it's a visible decision.52. How does
(string | number)[]differ fromstring[] | number[]?Correct answer: The first may mix both; the second holds only one type
Parentheses matter:
string | number[]would mean "a string or an array of numbers".53. What type does
const direction = 'left';get?Correct answer:
'left'A
constcan't be reassigned, so TypeScript keeps the literal. Withlet direction = 'left'it widens tostring.54. What is the type of
users.find((u) => u.id === id)ifusers: User[]?Correct answer:
User | undefinedfindmay not find anything, so you must handleundefinedbefore using the result.55. Why can
typeof value === 'object'be a trap when narrowing?Correct answer: It's also true for
nulland arraysCombine it with
value !== null, or useArray.isArrayfor arrays. TypeScript reflects this by keepingnullin the narrowed type.56. What does
if (count)miss whencount: number | undefined?Correct answer: It also excludes
0, a possibly valid valueTruthiness narrowing treats
0,''andNaNas false. Usecount !== undefinedwhen zero is meaningful.57. How does
instanceofhelp with types?if (err instanceof HttpError) { console.log(err.status); }Correct answer: It narrows the value to the class type
instanceofchecks the prototype chain at runtime, so it works with classes, not with interfaces or type aliases (they don't exist at runtime).58. Why can't you check
if (data is User)at runtime?Correct answer: Types are erased at compile time; you need runtime code
TypeScript only checks code at compile time. Data from APIs,
localStorageor forms must be validated by real code.59. What does
Readonly<User>do?Correct answer: Makes all properties of
Userread-only (shallowly)Nested objects remain mutable. At runtime nothing changes; use
Object.freezeif you need runtime protection.60. What does
Record<'draft' | 'published', number>require?Correct answer: Both keys present, each holding a number
With a union of literal keys,
Recordguarantees that no case is forgotten - adding a new status shows errors where it's missing.61. What type does
const items = [];get withstrictenabled?Correct answer: An evolving
any[], typed by what you pushExplicit annotation documents intent and prevents surprises when the array is returned or passed elsewhere.
62. How do you call a generic function with an explicit type argument?
const value = parse<User>(json);Correct answer: Pass the type in angle brackets after the name
Usually TypeScript infers type arguments from the values. Explicit arguments help when there is nothing to infer from.
63. How do you write a reusable type for an event handler function?
type Handler = (event: MouseEvent) => void;Correct answer: With a type alias for a function type
The same can be written as an interface with a call signature, but a type alias is shorter for plain functions.
64. Why can
[1, 2].forEach((n) => console.log(n))pass a callback with one parameter whenforEachpasses three?Correct answer: A function with fewer parameters is assignable; extra arguments are ignored
This mirrors common JavaScript practice. The opposite (a callback requiring more parameters than provided) is an error.
65. What's the result type of
user?.address?.cityifcity: string?Correct answer:
string | undefinedOptional chaining stops at the first
null/undefinedand returnsundefined, so the result type includes it.66. What is the type of
const port = env.PORT ?? 3000ifenv.PORT: string | undefined?Correct answer:
string | number??removesundefined/nullfrom the left side and adds the type of the right side. Convert withNumber(...)if you need a number.67. What type does
await (await fetch(url)).json()have?Correct answer:
any- you should annotate or validate the resultResponse.json()returnsPromise<any>. Assign it to a typed variable or, better, parse it with a schema to catch API changes.68. What does
document.createElement('canvas')return in TypeScript?Correct answer:
HTMLCanvasElement- the type follows the tag nameThe DOM types have an overload keyed by
HTMLElementTagNameMap:'canvas'givesHTMLCanvasElementwithgetContext,'input'givesHTMLInputElement. An unknown tag name returns plainHTMLElement. UnlikequerySelector,createElementnever returnsnull.69. Are
Array<string>andstring[]different types?Correct answer: No - two syntaxes for the same type
Teams usually pick one style for consistency. For read-only arrays the equivalents are
ReadonlyArray<string>andreadonly string[].70. How do you check types in CI when a bundler (Vite, esbuild) already compiles TS without type checking?
Correct answer: Run
tsc --noEmitas a separate stepFast bundlers only strip types. A separate
tscrun (orvue-tscfor Vue) catches type errors without producing files.71. How does an optional property
name?: stringdiffer fromname: string | undefined?Correct answer:
?allows omitting the property;| undefineddoesn'tThe difference matters when creating objects:
{}is valid for the first type but not for the second.72. How do you describe an object with a method in a type?
interface Logger { log(message: string): void; level: 'info' | 'debug'; }Correct answer: Method syntax:
log(message: string): voidBoth method and property syntax work. With
strictFunctionTypes, property syntax gets stricter parameter checks.73. Can recent Node.js versions run a
.tsfile directly?Correct answer: Yes - it strips types, but doesn't type-check
Type stripping removes types without transformation, so features that generate code (like
enum) need extra flags or a compiler.74. What type does a function parameter with a default value get?
function paginate(page = 1) { /* ... */ }Correct answer: Inferred from the default, optional for callers
Callers may omit the argument or pass
undefined; inside the functionpageis always anumber.75. Why is
@ts-expect-errorsafer than@ts-ignore?Correct answer: It errors once the next line has no error left
Both silence the next line. Add a comment explaining why, and prefer fixing types where possible.