TypeScript Objects Practice Programs with Solutions (31 Programs)

Practise TypeScript objects with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Objects lesson first.

TypeScript Beginner Programs

1. Inline object typeBeginner

Annotate a user object with an inline type and print its fields.

Show solution
const user: { name: string; age: number } = { name: 'Ana', age: 29 };
console.log(`${user.name} is ${user.age}`);

Output

Ana is 29

Explanation: the inline type lists each property and its type, so the object must match it exactly.

2. Missing property is a compile errorBeginner

Show that leaving out a required property is rejected.

Show solution
type Credentials = { username: string; password: string };
const ok: Credentials = { username: 'qa', password: 'secret' };
console.log(ok.username);
// @ts-expect-error: Property 'password' is missing in type '{ username: string; }'
const broken: Credentials = { username: 'qa' };
console.log(broken.username);

Output

qa
qa

Explanation: every property in the type is required unless marked optional, so a missing field fails to compile.

3. Type alias for an objectBeginner

Name an object shape with type and reuse it for two values.

Show solution
type Product = { sku: string; price: number };
const pen: Product = { sku: 'PEN-1', price: 1.5 };
const book: Product = { sku: 'BK-7', price: 12 };
console.log(`${pen.sku} + ${book.sku} = ${pen.price + book.price}`);

Output

PEN-1 + BK-7 = 13.5

Explanation: a type alias gives the shape a name, so you write it once and use it everywhere.

4. Optional propertyBeginner

Make phone optional and print a fallback when it is missing.

Show solution
type Contact = { email: string; phone?: string };
const contacts: Contact[] = [{ email: 'a@test.io', phone: '555-0101' }, { email: 'b@test.io' }];
for (const c of contacts) console.log(`${c.email}: ${c.phone ?? 'no phone'}`);

Output

a@test.io: 555-0101
b@test.io: no phone

Explanation: phone?: string means the property may be absent, so its type is string | undefined and needs a fallback.

5. Readonly propertyBeginner

Mark an id as readonly and show that it cannot be reassigned.

Show solution
type Order = { readonly id: number; status: string };
const order: Order = { id: 7, status: 'new' };
order.status = 'shipped';
// @ts-expect-error: Cannot assign to 'id' because it is a read-only property
const change = () => (order.id = 8);
console.log(order.id, order.status, typeof change);

Output

7 shipped function

Explanation: readonly blocks reassignment at compile time while other properties stay editable.

6. Excess property checkBeginner

Show that an object literal with an unknown property is rejected.

Show solution
type Point = { x: number; y: number };
const p: Point = { x: 1, y: 2 };
// @ts-expect-error: Object literal may only specify known properties, and 'z' does not exist in type 'Point'
const q: Point = { x: 1, y: 2, z: 3 };
console.log(p.x + p.y, q.x);

Output

3 1

Explanation: fresh object literals are checked for extra properties, which catches typos such as tiemout instead of timeout.

7. Nested object typeBeginner

Type a test config that contains a nested viewport object.

Show solution
type Config = { baseURL: string; viewport: { width: number; height: number } };
const config: Config = { baseURL: 'https://example.com', viewport: { width: 1280, height: 720 } };
console.log(`${config.baseURL} at ${config.viewport.width}x${config.viewport.height}`);

Output

https://example.com at 1280x720

Explanation: nested properties are typed too, so config.viewport.width is known to be a number.

8. Destructure with typesBeginner

Destructure a typed object and rename one property.

Show solution
type Env = { name: string; url: string; retries: number };
const env: Env = { name: 'staging', url: 'https://staging.example.com', retries: 2 };
const { name: envName, retries } = env;
console.log(`${envName} uses ${retries} retries`);

Output

staging uses 2 retries

Explanation: destructured variables take their types from the object, and name: envName renames while keeping the type.

9. Object method with typed parametersBeginner

Add a typed method to an object and call it.

Show solution
const calculator = {
  rate: 0.2,
  tax(amount: number): number {
    return Math.round(amount * this.rate * 100) / 100;
  },
};
console.log(calculator.tax(49.99));

Output

10

Explanation: methods in object literals can type their parameters and return value, and this refers to the object.

10. Object property access by a known keyBeginner

Read a property with bracket notation using a key typed as keyof.

Show solution
type Limits = { timeout: number; retries: number; workers: number };
const limits: Limits = { timeout: 30000, retries: 2, workers: 4 };
const key: keyof Limits = 'workers';
console.log(`${key} = ${limits[key]}`);

Output

workers = 4

Explanation: keyof Limits is 'timeout' | 'retries' | 'workers', so the lookup is safe and returns a number.

TypeScript Intermediate Programs

11. Record for a dictionaryIntermediate

Store status messages in Record<number, string> and look them up.

Show solution
const messages: Record<number, string> = { 200: 'OK', 404: 'Not Found', 500: 'Server Error' };
for (const code of [200, 404, 418]) console.log(`${code}: ${messages[code] ?? 'Unknown'}`);

Output

200: OK
404: Not Found
418: Unknown

Explanation: Record&lt;K, V&gt; describes an object used as a lookup table. A missing key still returns undefined at runtime, hence the fallback.

12. Record with a union of keysIntermediate

Require one timeout for every browser by keying a Record on a union.

Show solution
type Browser = 'chromium' | 'firefox' | 'webkit';
const timeouts: Record<Browser, number> = { chromium: 30000, firefox: 45000, webkit: 40000 };
console.log(Object.entries(timeouts).map(([b, t]) => `${b}=${t / 1000}s`).join(', '));
// @ts-expect-error: Property 'webkit' is missing in type '{ chromium: number; firefox: number; }'
const partial: Record<Browser, number> = { chromium: 1, firefox: 2 };
console.log(Object.keys(partial).length);

Output

chromium=30s, firefox=45s, webkit=40s
2

Explanation: when the keys are a union, every member must be present, so adding a browser later forces you to update the map.

13. Index signatureIntermediate

Allow any string key for custom HTTP headers.

Show solution
type Headers = { [name: string]: string };
const headers: Headers = { Accept: 'application/json' };
headers['X-Trace-Id'] = 'abc123';
for (const [k, v] of Object.entries(headers)) console.log(`${k}: ${v}`);

Output

Accept: application/json
X-Trace-Id: abc123

Explanation: an index signature says “any key of this type, with values of that type”, useful when keys are not known in advance.

14. Spread to copy and overrideIntermediate

Create a new config from defaults and overrides with spread.

Show solution
type RunConfig = { browser: string; headless: boolean; retries: number };
const defaults: RunConfig = { browser: 'chromium', headless: true, retries: 0 };
const ci: RunConfig = { ...defaults, retries: 2 };
console.log(defaults.retries, ci.retries, ci.browser);

Output

0 2 chromium

Explanation: spread copies properties into a new object, later properties win, and the result is still checked against RunConfig.

15. Partial for updatesIntermediate

Write update(user, changes) where changes may hold any subset of fields.

Show solution
type User = { name: string; email: string; active: boolean };
function update(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}
const before: User = { name: 'Ben', email: 'ben@test.io', active: true };
const after = update(before, { active: false });
console.log(after.name, after.active, before.active);

Output

Ben false true

Explanation: Partial&lt;User&gt; makes every property optional, which fits patch-style updates.

16. Required removes optionalIntermediate

Turn an options type with optional fields into a fully filled one.

Show solution
type Options = { timeout?: number; retries?: number };
function withDefaults(o: Options): Required<Options> {
  return { timeout: o.timeout ?? 30000, retries: o.retries ?? 0 };
}
const full = withDefaults({ retries: 3 });
console.log(`timeout ${full.timeout / 1000}s, retries ${full.retries}`);

Output

timeout 30s, retries 3

Explanation: Required&lt;Options&gt; guarantees both numbers exist, so callers can use them without checking for undefined.

17. Pick and OmitIntermediate

Build a public profile type that leaves out the password.

Show solution
type Account = { id: number; email: string; password: string; role: string };
type PublicAccount = Omit<Account, 'password'>;
type Login = Pick<Account, 'email' | 'password'>;
const pub: PublicAccount = { id: 1, email: 'qa@test.io', role: 'admin' };
const login: Login = { email: 'qa@test.io', password: 'x' };
console.log(Object.keys(pub).join(','), Object.keys(login).join(','));

Output

id,email,role email,password

Explanation: Omit and Pick derive new types from an existing one, so they stay in sync when Account changes.

18. Readonly utility typeIntermediate

Freeze a settings object type with Readonly&lt;T&gt;.

Show solution
type Settings = { theme: string; lang: string };
const settings: Readonly<Settings> = { theme: 'dark', lang: 'en' };
// @ts-expect-error: Cannot assign to 'theme' because it is a read-only property
const change = () => (settings.theme = 'light');
console.log(settings.theme, typeof change);

Output

dark function

Explanation: Readonly&lt;T&gt; marks every property readonly in one step. Use Object.freeze too if you need runtime protection.

19. keyof with a generic getterIntermediate

Write getProp(obj, key) that only accepts keys that exist.

Show solution
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const test = { title: 'login', retries: 2, tags: ['smoke'] };
console.log(getProp(test, 'title').toUpperCase());
console.log(getProp(test, 'retries') + 1);

Output

LOGIN
3

Explanation: K extends keyof T limits the key, and T[K] gives the exact property type, so title is a string and retries a number.

20. Object.entries with typed valuesIntermediate

Print a score table and compute the total.

Show solution
const scores: Record<string, number> = { ana: 92, ben: 78, cai: 85 };
let total = 0;
for (const [student, score] of Object.entries(scores)) {
  total += score;
  console.log(`${student}: ${score}`);
}
console.log(`average ${(total / Object.keys(scores).length).toFixed(1)}`);

Output

ana: 92
ben: 78
cai: 85
average 85.0

Explanation: with a Record value type, Object.entries returns [string, number][], so score is a number.

21. Optional chaining on nested objectsIntermediate

Read a deeply nested optional value safely.

Show solution
type Response = { data?: { user?: { name: string } } };
const full: Response = { data: { user: { name: 'Ana' } } };
const empty: Response = {};
console.log(full.data?.user?.name ?? 'anonymous');
console.log(empty.data?.user?.name ?? 'anonymous');

Output

Ana
anonymous

Explanation: ?. stops at the first undefined and returns undefined, and the type of the chain includes undefined to match.

22. Object comparison by valueIntermediate

Compare two flat objects field by field.

Show solution
function shallowEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
  const ka = Object.keys(a);
  const kb = Object.keys(b);
  return ka.length === kb.length && ka.every(k => a[k] === b[k]);
}
const a = { id: 1, status: 'ok' };
const copy = { ...a };
console.log(a === copy, shallowEqual(a, copy), shallowEqual(a, { id: 1, status: 'err' }));

Output

false true false

Explanation: === compares object references, not contents. unknown values can still be compared with === without any casts.

TypeScript Real-World QA Scenario Programs

23. Deep merge of configReal-world

Merge nested overrides into a default config without changing the defaults.

Show solution
type Cfg = { use: { headless: boolean; viewport: { width: number; height: number } }; retries: number };
type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };
const base: Cfg = { use: { headless: true, viewport: { width: 1280, height: 720 } }, retries: 0 };
function merge(cfg: Cfg, o: DeepPartial<Cfg>): Cfg {
  return {
    retries: o.retries ?? cfg.retries,
    use: {
      headless: o.use?.headless ?? cfg.use.headless,
      viewport: { ...cfg.use.viewport, ...o.use?.viewport },
    },
  };
}
const mobile = merge(base, { use: { viewport: { width: 390 } } });
console.log(mobile.use.viewport.width, mobile.use.viewport.height, base.use.viewport.width);

Output

390 720 1280

Explanation: a recursive mapped type makes every nested property optional, so callers can override just one deep field.

24. Mapped type for flagsReal-world

Create a type with a boolean flag for each feature name.

Show solution
type Feature = 'darkMode' | 'beta' | 'chat';
type Flags = { [F in Feature]: boolean };
const flags: Flags = { darkMode: true, beta: false, chat: true };
const enabled = (Object.keys(flags) as Feature[]).filter(f => flags[f]);
console.log(`enabled: ${enabled.join(', ')}`);

Output

enabled: darkMode, chat

Explanation: a mapped type builds properties from a union, so the object must have exactly one flag per feature.

25. Type-safe object keys helperReal-world

Write a keys helper that returns (keyof T)[] instead of string[].

Show solution
function keys<T extends object>(obj: T): (keyof T)[] {
  return Object.keys(obj) as (keyof T)[];
}
const report = { passed: 18, failed: 2, skipped: 1 };
for (const k of keys(report)) console.log(`${k.padEnd(8)}${report[k]}`);

Output

passed  18
failed  2
skipped 1

Explanation: Object.keys returns string[] because objects may have extra keys at runtime. When you know the shape, a typed helper lets you index without errors.

26. Discriminated union of objectsReal-world

Handle API results that are either success or error objects.

Show solution
type ApiResult =
  | { ok: true; data: { id: number } }
  | { ok: false; error: string };
function describe(r: ApiResult): string {
  return r.ok ? `created #${r.data.id}` : `failed: ${r.error}`;
}
console.log(describe({ ok: true, data: { id: 42 } }));
console.log(describe({ ok: false, error: '401 Unauthorized' }));

Output

created #42
failed: 401 Unauthorized

Explanation: checking the shared ok property narrows the union, so data is only reachable on success and error only on failure.

27. satisfies keeps literal typesReal-world

Check a route table against a type while keeping its exact keys.

Show solution
type Route = { path: string; auth: boolean };
const routes = {
  home: { path: '/', auth: false },
  account: { path: '/account', auth: true },
} satisfies Record<string, Route>;
console.log(routes.account.path, Object.keys(routes).length);
// @ts-expect-error: Property 'admin' does not exist on type
const missing = () => routes.admin;
console.log(typeof missing);

Output

/account 2
function

Explanation: satisfies checks the shape but keeps the inferred type, so unknown keys like admin are still caught, unlike a plain Record&lt;string, Route&gt; annotation.

28. Build an object from entriesReal-world

Convert an array of [name, value] cookie pairs into a typed object.

Show solution
const pairs: [string, string][] = [['session', 'abc'], ['theme', 'dark'], ['lang', 'en']];
const cookies: Record<string, string> = Object.fromEntries(pairs);
console.log(cookies.theme, Object.keys(cookies).length);

Output

dark 3

Explanation: Object.fromEntries turns pairs back into an object, the reverse of Object.entries.

29. Freeze test data at runtime and compile timeReal-world

Combine as const and Object.freeze for fixed test users.

Show solution
const USERS = Object.freeze({
  admin: { email: 'admin@test.io', role: 'admin' },
  viewer: { email: 'viewer@test.io', role: 'viewer' },
} as const);
type Role = (typeof USERS)[keyof typeof USERS]['role'];
const role: Role = USERS.viewer.role;
console.log(role, Object.isFrozen(USERS));

Output

viewer true

Explanation: as const gives readonly literal types for the compiler, Object.freeze stops changes at runtime, and the role union is derived from the data.

30. Pick properties at runtime with typesReal-world

Write a generic pick(obj, keys) that returns only the chosen fields.

Show solution
function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  const out = {} as Pick<T, K>;
  for (const k of keys) out[k] = obj[k];
  return out;
}
const fullUser = { id: 9, email: 'cai@test.io', password: 'hidden', role: 'qa' };
const safe = pick(fullUser, ['id', 'email', 'role']);
console.log(JSON.stringify(safe));

Output

{"id":9,"email":"cai@test.io","role":"qa"}

Explanation: the return type Pick&lt;T, K&gt; matches exactly the keys passed in, so safe.password would be a compile error.

31. Count fields by value typeReal-world

Summarise an object’s values by their runtime type.

Show solution
function typeSummary(obj: Record<string, unknown>): Record<string, number> {
  const out: Record<string, number> = {};
  for (const v of Object.values(obj)) {
    const t = Array.isArray(v) ? 'array' : v === null ? 'null' : typeof v;
    out[t] = (out[t] ?? 0) + 1;
  }
  return out;
}
const payload = { id: 1, name: 'x', tags: ['a'], active: true, note: null, score: 9.5 };
console.log(JSON.stringify(typeSummary(payload)));

Output

{"number":2,"string":1,"array":1,"boolean":1,"null":1}

Explanation: values typed as unknown must be checked before use, which is the safe way to handle data from an API.

Keep Practising

TypeScript Arrays and Tuples Practice Programs with Solutions (31 Programs)

Practise TypeScript arrays and tuples with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Arrays lesson first.

TypeScript Beginner Programs

1. Declare typed arraysBeginner

Declare a string[] of browsers and a number[] of timeouts, then print their lengths.

Show solution
const browsers: string[] = ['chromium', 'firefox', 'webkit'];
const timeouts: number[] = [5000, 10000, 30000];
console.log(browsers.length, timeouts.length);
console.log(browsers[0], timeouts[2]);

Output

3 3
chromium 30000

Explanation: the element type is fixed by the annotation, so every item is checked when the array is created.

2. Wrong element types are compile errorsBeginner

Show that pushing a number into a string[] is rejected.

Show solution
const tags: string[] = ['@smoke'];
tags.push('@regression');
// @ts-expect-error: Argument of type 'number' is not assignable to parameter of type 'string'
tags.push(42);
console.log(tags.length);

Output

3

Explanation: the compiler stops the bad push. The line still runs here for the demo, which is why the length is 3; in a real build the error would stop you first.

3. Array<T> generic syntaxBeginner

Declare the same kind of array with Array&lt;number&gt; and sum it.

Show solution
const scores: Array<number> = [90, 75, 88];
let total = 0;
for (const s of scores) total += s;
console.log(`total ${total}, average ${(total / scores.length).toFixed(1)}`);

Output

total 253, average 84.3

Explanation: Array&lt;number&gt; and number[] mean exactly the same thing. Most code uses number[]; the generic form reads better for complex types.

4. Inferred array typeBeginner

Let TypeScript infer the type of an array literal and use a string method on an item.

Show solution
const pages = ['home', 'login', 'cart'];
const upper = pages.map(p => p.toUpperCase());
console.log(upper.join(' | '));

Output

HOME | LOGIN | CART

Explanation: the literal is inferred as string[], so p is a string inside map without any annotation.

5. Union element typeBeginner

Store test ids that may be numbers or strings and print each with its type.

Show solution
const ids: (string | number)[] = [101, 'TC-202', 303];
for (const id of ids) console.log(`${id} is ${typeof id}`);

Output

101 is number
TC-202 is string
303 is number

Explanation: the parentheses matter: (string | number)[] is an array of mixed items, while string | number[] would mean a string or an array of numbers.

6. Readonly arrayBeginner

Create a readonly string[] of environments and show that it cannot be changed.

Show solution
const envs: readonly string[] = ['dev', 'staging', 'prod'];
console.log(envs.includes('staging'));
// @ts-expect-error: Property 'push' does not exist on type 'readonly string[]'
const add = () => envs.push('qa');
console.log(envs.length, typeof add);

Output

true
3 function

Explanation: a readonly array has no mutating methods in its type, so push, pop and index assignment fail to compile.

7. Tuple for a key-value pairBeginner

Model a header as a [string, string] tuple and print it.

Show solution
const header: [string, string] = ['Content-Type', 'application/json'];
const [name, value] = header;
console.log(`${name}: ${value}`);

Output

Content-Type: application/json

Explanation: a tuple fixes both the length and the type at each position, and destructuring keeps those types.

8. Tuple with mixed typesBeginner

Store a test result as [string, boolean, number].

Show solution
const result: [string, boolean, number] = ['login test', true, 1240];
const [title, passed, ms] = result;
console.log(`${title}: ${passed ? 'PASS' : 'FAIL'} in ${ms}ms`);

Output

login test: PASS in 1240ms

Explanation: each position has its own type, so passed is a boolean and ms is a number after destructuring.

9. Filter with a typed callbackBeginner

Keep only the failed tests from a list of statuses.

Show solution
const statuses: string[] = ['passed', 'failed', 'passed', 'skipped', 'failed'];
const failed = statuses.filter(s => s === 'failed');
console.log(`${failed.length} failed of ${statuses.length}`);

Output

2 failed of 5

Explanation: filter returns the same element type, string[], so the result needs no annotation.

10. Map numbers to stringsBeginner

Turn durations in milliseconds into labelled seconds.

Show solution
const durations: number[] = [1200, 450, 3100];
const labels: string[] = durations.map(ms => `${(ms / 1000).toFixed(2)}s`);
console.log(labels.join(', '));

Output

1.20s, 0.45s, 3.10s

Explanation: map changes the element type from number to string, and the annotation on labels confirms it.

TypeScript Intermediate Programs

11. reduce with a typed accumulatorIntermediate

Total the run time of tests with reduce.

Show solution
const runs: number[] = [320, 1500, 780, 95];
const totalMs = runs.reduce((sum: number, ms: number) => sum + ms, 0);
console.log(`total ${totalMs}ms`);

Output

total 2695ms

Explanation: the starting value 0 gives the accumulator its number type, so the result is a number.

12. find returns T | undefinedIntermediate

Find a user by role and handle the case where none matches.

Show solution
const users: string[] = ['admin@test.io', 'viewer@test.io'];
const editor = users.find(u => u.startsWith('editor'));
console.log(editor ?? 'no editor found');
const admin = users.find(u => u.startsWith('admin'));
if (admin) console.log(admin.toUpperCase());

Output

no editor found
ADMIN@TEST.IO

Explanation: find returns string | undefined, so TypeScript makes you check the result before calling string methods on it.

13. Array of objectsIntermediate

Type a list of test cases and print the ones tagged as smoke tests.

Show solution
type TestCase = { id: number; title: string; tags: string[] };
const cases: TestCase[] = [
  { id: 1, title: 'login', tags: ['smoke'] },
  { id: 2, title: 'search', tags: ['regression'] },
  { id: 3, title: 'checkout', tags: ['smoke', 'payments'] },
];
const smoke = cases.filter(c => c.tags.includes('smoke')).map(c => c.title);
console.log(smoke.join(', '));

Output

login, checkout

Explanation: once the element type is named, every callback knows the shape of c, and misspelled properties fail to compile.

14. Sort numbers correctlyIntermediate

Sort response times in ascending order.

Show solution
const times: number[] = [250, 1200, 90, 400];
const sorted = [...times].sort((a, b) => a - b);
console.log(sorted.join(' < '));
console.log(times.join(', '));

Output

90 < 250 < 400 < 1200
250, 1200, 90, 400

Explanation: without a compare function sort compares as strings, so 1200 would come before 250. Copying with spread keeps the original untouched.

15. Sort objects by a propertyIntermediate

Sort test results from slowest to fastest.

Show solution
type Result = { name: string; ms: number };
const results: Result[] = [
  { name: 'login', ms: 820 },
  { name: 'search', ms: 2100 },
  { name: 'logout', ms: 300 },
];
results.sort((a, b) => b.ms - a.ms);
console.log(results.map(r => `${r.name}:${r.ms}`).join(' '));

Output

search:2100 login:820 logout:300

Explanation: the compare function is typed from Result, so a.ms and b.ms are numbers.

16. Remove duplicates with SetIntermediate

Remove duplicate tags while keeping a string[] type.

Show solution
const tags: string[] = ['smoke', 'ui', 'smoke', 'api', 'ui'];
const unique: string[] = [...new Set(tags)];
console.log(unique.join(', '));

Output

smoke, ui, api

Explanation: new Set(tags) is a Set&lt;string&gt;, and spreading it back gives a string[].

17. Type guard in filterIntermediate

Remove null values from a list and get a string[] back.

Show solution
const raw: (string | null)[] = ['a@test.io', null, 'b@test.io', null];
const emails = raw.filter((e): e is string => e !== null);
console.log(emails.map(e => e.toUpperCase()).join(', '));

Output

A@TEST.IO, B@TEST.IO

Explanation: the e is string predicate tells TypeScript the result is string[]. Without it the type would stay (string | null)[].

18. Optional tuple elementIntermediate

Model a viewport as [width, height, scale?].

Show solution
type Viewport = [number, number, number?];
const desktop: Viewport = [1280, 720];
const retina: Viewport = [1440, 900, 2];
for (const [w, h, scale = 1] of [desktop, retina]) console.log(`${w}x${h} @${scale}x`);

Output

1280x720 @1x
1440x900 @2x

Explanation: the ? makes the last position optional, and a default in the destructuring fills it in.

19. Named tuple elementsIntermediate

Use labelled tuple members to describe a retry setting.

Show solution
type RetryPolicy = [attempts: number, delayMs: number];
const policy: RetryPolicy = [3, 500];
const [attempts, delayMs] = policy;
console.log(`retry ${attempts} times every ${delayMs}ms`);

Output

retry 3 times every 500ms

Explanation: labels do not change the runtime value, but they show up in editor hints, which makes tuples self-documenting.

20. Readonly tuple with as constIntermediate

Freeze a list of browsers with as const and use it as a union type.

Show solution
const BROWSERS = ['chromium', 'firefox', 'webkit'] as const;
type Browser = (typeof BROWSERS)[number];
function launch(b: Browser): string {
  return `launching ${b}`;
}
console.log(launch('firefox'));
console.log(BROWSERS.length);

Output

launching firefox
3

Explanation: as const makes a readonly tuple of literal types, and [number] turns it into the union 'chromium' | 'firefox' | 'webkit'.

21. Rest elements in a tupleIntermediate

Type a log line as a level followed by any number of messages.

Show solution
type LogLine = [level: 'info' | 'error', ...messages: string[]];
const lines: LogLine[] = [
  ['info', 'page loaded'],
  ['error', 'timeout', 'retrying'],
];
for (const [level, ...msgs] of lines) console.log(`[${level}] ${msgs.join(' / ')}`);

Output

[info] page loaded
[error] timeout / retrying

Explanation: a rest element lets a tuple have a fixed start and a variable tail, still fully typed.

22. Two-dimensional arrayIntermediate

Store a small test data grid as string[][] and print it.

Show solution
const grid: string[][] = [
  ['user', 'role'],
  ['ana', 'admin'],
  ['ben', 'viewer'],
];
for (const row of grid) console.log(row.join(' | '));
console.log(`rows ${grid.length}, cols ${grid[0].length}`);

Output

user | role
ana | admin
ben | viewer
rows 3, cols 2

Explanation: string[][] is an array whose items are string[], so each row has array methods.

TypeScript Real-World QA Scenario Programs

23. Group items into a recordReal-world

Group test names by status into Record&lt;string, string[]&gt;.

Show solution
type Run = { name: string; status: 'passed' | 'failed' | 'skipped' };
const runs: Run[] = [
  { name: 'login', status: 'passed' },
  { name: 'cart', status: 'failed' },
  { name: 'search', status: 'passed' },
  { name: 'profile', status: 'skipped' },
];
const byStatus: Record<string, string[]> = {};
for (const r of runs) (byStatus[r.status] ??= []).push(r.name);
for (const [status, names] of Object.entries(byStatus)) console.log(`${status}: ${names.join(', ')}`);

Output

passed: login, search
failed: cart
skipped: profile

Explanation: ??= creates the list the first time a status appears, and the record type keeps every value a string[].

24. Chunk an array genericallyReal-world

Split a list of test files into batches of a given size.

Show solution
function chunk<T>(items: T[], size: number): T[][] {
  const out: T[][] = [];
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
  return out;
}
const files = ['a.spec', 'b.spec', 'c.spec', 'd.spec', 'e.spec'];
chunk(files, 2).forEach((batch, i) => console.log(`worker ${i + 1}: ${batch.join(', ')}`));

Output

worker 1: a.spec, b.spec
worker 2: c.spec, d.spec
worker 3: e.spec

Explanation: the generic T means the same function chunks strings, numbers or objects, and the result keeps the element type.

25. Generic last-item helperReal-world

Write last&lt;T&gt;(items: T[]): T | undefined.

Show solution
function last<T>(items: readonly T[]): T | undefined {
  return items[items.length - 1];
}
console.log(last(['step 1', 'step 2', 'step 3']));
console.log(last([10, 20]));
console.log(last([]) ?? 'empty');

Output

step 3
20
empty

Explanation: the return type includes undefined because the array may be empty. Taking readonly T[] lets callers pass frozen arrays too.

26. Zip two arrays into tuplesReal-world

Pair test names with their durations.

Show solution
function zip<A, B>(a: A[], b: B[]): [A, B][] {
  const n = Math.min(a.length, b.length);
  const out: [A, B][] = [];
  for (let i = 0; i < n; i++) out.push([a[i], b[i]]);
  return out;
}
const pairs = zip(['login', 'search', 'cart'], [820, 2100, 640]);
for (const [name, ms] of pairs) console.log(`${name.padEnd(7)}${ms}ms`);

Output

login  820ms
search 2100ms
cart   640ms

Explanation: two type parameters keep each side’s type, so name is a string and ms is a number in the loop.

27. Partition into pass and failReal-world

Split results into two arrays in one pass, returning a tuple.

Show solution
function partition<T>(items: T[], test: (item: T) => boolean): [T[], T[]] {
  const yes: T[] = [];
  const no: T[] = [];
  for (const item of items) (test(item) ? yes : no).push(item);
  return [yes, no];
}
const codes = [200, 404, 201, 500, 204];
const [ok, bad] = partition(codes, c => c < 400);
console.log(`ok: ${ok.join(',')} | bad: ${bad.join(',')}`);

Output

ok: 200,201,204 | bad: 404,500

Explanation: returning a tuple [T[], T[]] lets the caller destructure both groups with the right types.

28. Count by key with a MapReal-world

Count how many times each error message appears.

Show solution
const errors: string[] = ['timeout', 'not found', 'timeout', 'timeout', 'not found', 'crash'];
const counts = new Map<string, number>();
for (const e of errors) counts.set(e, (counts.get(e) ?? 0) + 1);
const top = [...counts].sort((a, b) => b[1] - a[1]);
for (const [msg, n] of top) console.log(`${n} x ${msg}`);

Output

3 x timeout
2 x not found
1 x crash

Explanation: Map&lt;string, number&gt; keeps keys and counts typed, and spreading a map gives [string, number][] for sorting.

29. Flatten nested arraysReal-world

Flatten a list of test suites into one list of tests.

Show solution
const suites: string[][] = [['login', 'logout'], ['search'], ['cart', 'checkout']];
const tests: string[] = suites.flat();
console.log(`${tests.length} tests: ${tests.join(', ')}`);
const steps = suites.flatMap(s => s.map(t => `run ${t}`));
console.log(steps[0], '...', steps[steps.length - 1]);

Output

5 tests: login, logout, search, cart, checkout
run login ... run checkout

Explanation: flat() on string[][] returns string[], and flatMap maps and flattens one level in a single call.

30. Pass rate per suiteReal-world

Compute the pass rate for each suite from a typed array of results.

Show solution
type Outcome = { suite: string; passed: boolean };
const outcomes: Outcome[] = [
  { suite: 'auth', passed: true },
  { suite: 'auth', passed: false },
  { suite: 'cart', passed: true },
  { suite: 'cart', passed: true },
];
const stats = new Map<string, [pass: number, total: number]>();
for (const o of outcomes) {
  const [pass, total] = stats.get(o.suite) ?? [0, 0];
  stats.set(o.suite, [pass + (o.passed ? 1 : 0), total + 1]);
}
for (const [suite, [pass, total]] of stats) console.log(`${suite}: ${Math.round((pass / total) * 100)}%`);

Output

auth: 50%
cart: 100%

Explanation: storing a named tuple in the map keeps two related numbers together with clear labels.

31. Readonly parameter protects the callerReal-world

Write a function that returns a sorted copy without changing a readonly input.

Show solution
function sortedCopy(values: readonly number[]): number[] {
  // @ts-expect-error: Property 'sort' does not exist on type 'readonly number[]'
  const misuse = () => values.sort();
  return [...values].sort((a, b) => a - b);
}
const original = [3, 1, 2] as const;
console.log(sortedCopy(original).join(','), original.join(','));

Output

1,2,3 3,1,2

Explanation: sort changes the array in place, so it is not allowed on a readonly type. Copy first, then sort; the caller’s data stays the same.

Keep Practising

TypeScript Functions Practice Programs with Solutions (31 Programs)

Practise TypeScript functions with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Functions lesson first.

TypeScript Beginner Programs

1. Typed parameters and return typeBeginner

Write add(a: number, b: number): number and call it.

Show solution
function add(a: number, b: number): number {
  return a + b;
}
console.log(add(12, 30));

Output

42

Explanation: annotating parameters and the return type documents the contract and lets the compiler check every call.

2. Wrong argument types are compile errorsBeginner

Show that passing a string to a number parameter is rejected.

Show solution
function square(n: number): number {
  return n * n;
}
console.log(square(9));
// @ts-expect-error: Argument of type 'string' is not assignable to parameter of type 'number'
console.log(square('9'));

Output

81
81

Explanation: the call with a string fails to compile. In plain JavaScript '9' * '9' would silently coerce to 81, hiding the bug.

3. Arrow function with typesBeginner

Write a typed arrow function that builds a full name.

Show solution
const fullName = (first: string, last: string): string => `${first} ${last}`;
console.log(fullName('Asha', 'Sharma'));

Output

Asha Sharma

Explanation: arrow functions take the same parameter and return annotations as regular functions.

4. Optional parameterBeginner

Write greet(name, title?) where the title is optional.

Show solution
function greet(name: string, title?: string): string {
  return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
console.log(greet('Ravi'));
console.log(greet('Ravi', 'Dr.'));

Output

Hello, Ravi
Hello, Dr. Ravi

Explanation: title? has the type string | undefined, so the function checks it before using it.

5. Default parameterBeginner

Write openPage(path, timeout = 30000) and call it with and without a timeout.

Show solution
function openPage(path: string, timeout: number = 30000): string {
  return `${path} (${timeout} ms)`;
}
console.log(openPage('/login'));
console.log(openPage('/reports', 60000));

Output

/login (30000 ms)
/reports (60000 ms)

Explanation: a default value makes the parameter optional for callers but always a number inside the function.

6. void return typeBeginner

Write a logger that returns nothing.

Show solution
function logStep(step: string): void {
  console.log(`[STEP] ${step}`);
}
logStep('Open login page');
logStep('Submit form');

Output

[STEP] Open login page
[STEP] Submit form

Explanation: void tells callers not to use the return value.

7. Rest parametersBeginner

Write sum(...values: number[]) that adds any number of arguments.

Show solution
function sum(...values: number[]): number {
  return values.reduce((total, v) => total + v, 0);
}
console.log(sum(), sum(5), sum(1, 2, 3, 4));

Output

0 5 10

Explanation: a rest parameter collects the arguments into a typed array.

8. Return an objectBeginner

Return min, max and average from a function with an object return type.

Show solution
function stats(values: number[]): { min: number; max: number; avg: number } {
  const total = values.reduce((a, b) => a + b, 0);
  return { min: Math.min(...values), max: Math.max(...values), avg: total / values.length };
}
console.log(stats([120, 340, 95, 410]));

Output

{ min: 95, max: 410, avg: 241.25 }

Explanation: the return type describes the object, so callers get autocomplete for min, max and avg.

9. Function type aliasBeginner

Declare a Formatter type and implement two formatters.

Show solution
type Formatter = (value: number) => string;
const asCurrency: Formatter = v => `₹${v.toFixed(2)}`;
const asPercent: Formatter = v => `${(v * 100).toFixed(1)}%`;
console.log(asCurrency(1299.5), asPercent(0.925));

Output

₹1299.50 92.5%

Explanation: a function type describes parameters and return type once, and every assigned function must match it.

10. Boolean-returning helperBeginner

Write isValidEmail(value: string): boolean.

Show solution
function isValidEmail(value: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
console.log(isValidEmail('qa@test.com'), isValidEmail('qa@test'));

Output

true false

Explanation: helpers that return booleans read naturally inside if conditions and assertions.

TypeScript Intermediate Programs

11. Union parameter with narrowingIntermediate

Accept an ID as a number or a string and normalise it.

Show solution
function normaliseId(id: number | string): string {
  return typeof id === 'number' ? `ID-${id.toString().padStart(4, '0')}` : id.toUpperCase();
}
console.log(normaliseId(42), normaliseId('id-0042'));

Output

ID-0042 ID-0042

Explanation: narrowing with typeof lets one function handle both types safely.

12. Function overloadsIntermediate

Write parse(value) that returns a number for numeric strings and a boolean for 'true'/'false'.

Show solution
function parse(value: 'true' | 'false'): boolean;
function parse(value: string): number;
function parse(value: string): number | boolean {
  if (value === 'true' || value === 'false') return value === 'true';
  return Number(value);
}
const flag: boolean = parse('true');
const count: number = parse('42');
console.log(flag, count + 1);

Output

true 43

Explanation: overload signatures give each kind of call its own precise return type.

13. Callback parameterIntermediate

Write forEachResult(results, callback) with a typed callback.

Show solution
type Result = { name: string; passed: boolean };
function forEachResult(results: Result[], callback: (r: Result, index: number) => void): void {
  results.forEach((r, i) => callback(r, i));
}
forEachResult([{ name: 'login', passed: true }, { name: 'cart', passed: false }], (r, i) =>
  console.log(`${i + 1}. ${r.name}: ${r.passed ? 'pass' : 'fail'}`)
);

Output

1. login: pass
2. cart: fail

Explanation: the callback’s type gives the arrow function’s parameters their types automatically.

14. Higher-order function returning a functionIntermediate

Write makeMultiplier(factor) returning a typed function.

Show solution
function makeMultiplier(factor: number): (n: number) => number {
  return n => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(21), triple(7));

Output

42 21

Explanation: the return type (n: number) =&gt; number describes the function being returned.

15. Closure with private stateIntermediate

Create a typed counter with increment and reset.

Show solution
function createCounter(start: number = 0): { next: () => number; reset: () => void } {
  let count = start;
  return {
    next: () => ++count,
    reset: () => { count = start; }
  };
}
const counter = createCounter(10);
console.log(counter.next(), counter.next());
counter.reset();
console.log(counter.next());

Output

11 12
11

Explanation: count is captured by the closure and can only change through the returned methods.

16. Generic identity-style helperIntermediate

Write first&lt;T&gt;(items: T[]): T | undefined.

Show solution
function first<T>(items: T[]): T | undefined {
  return items[0];
}
const browser = first(['chromium', 'firefox']);
const score = first([98, 87]);
const none = first<string>([]);
console.log(browser?.toUpperCase(), score?.toFixed(1), none ?? 'empty');

Output

CHROMIUM 98.0 empty

Explanation: the type parameter T is inferred from the argument, so the return type matches the array’s element type.

17. Destructured parameter with defaultsIntermediate

Accept an options object with defaults.

Show solution
type Options = { retries?: number; timeout?: number; headless?: boolean };
function describe({ retries = 0, timeout = 30000, headless = true }: Options = {}): string {
  return `retries=${retries}, timeout=${timeout}, headless=${headless}`;
}
console.log(describe());
console.log(describe({ retries: 2, headless: false }));

Output

retries=0, timeout=30000, headless=true
retries=2, timeout=30000, headless=false

Explanation: destructuring in the parameter list with defaults keeps calls short when many settings are optional.

18. Recursion with typesIntermediate

Flatten nested arrays of numbers recursively.

Show solution
type Nested = number | Nested[];
function flatten(value: Nested): number[] {
  return Array.isArray(value) ? value.flatMap(flatten) : [value];
}
console.log(flatten([1, [2, [3, [4]]], 5]).join(','));

Output

1,2,3,4,5

Explanation: a recursive type alias describes arbitrarily nested data, and the recursive function mirrors it.

19. Assertion functionIntermediate

Write assertNumber(value) that narrows unknown after the call.

Show solution
function assertNumber(value: unknown, name: string): asserts value is number {
  if (typeof value !== 'number' || Number.isNaN(value)) throw new Error(`${name} must be a number`);
}
const raw: unknown = JSON.parse('{"workers": 4}').workers;
assertNumber(raw, 'workers');
console.log(raw * 2);

Output

8

Explanation: after assertNumber returns, TypeScript treats raw as a number.

20. Async function return typeIntermediate

Write an async function that returns Promise&lt;string&gt;.

Show solution
async function fetchTitle(path: string): Promise<string> {
  await new Promise(resolve => setTimeout(resolve, 10));
  return `Title of ${path}`;
}
const title: string = await fetchTitle('/home');
console.log(title);

Output

Title of /home

Explanation: an async function always returns a Promise. Awaiting it gives the inner type.

TypeScript Real-World QA Scenario Programs

21. Typed assertion helperReal-world

Write expectEqual&lt;T&gt;(actual, expected, label) that reports PASS or FAIL.

Show solution
function expectEqual<T>(actual: T, expected: T, label: string): boolean {
  const ok = actual === expected;
  console.log(`${ok ? 'PASS' : 'FAIL'} ${label}${ok ? '' : ` (expected ${String(expected)}, got ${String(actual)})`}`);
  return ok;
}
expectEqual('Shop'.length, 4, 'title length');
expectEqual('cart'.toUpperCase(), 'CART', 'upper case');
expectEqual(0.1 + 0.2, 0.3, 'float sum');

Output

PASS title length
PASS upper case
FAIL float sum (expected 0.3, got 0.30000000000000004)

Explanation: the generic T makes actual and expected the same type, like Playwright’s expect(actual).toBe(expected).

22. URL builderReal-world

Write buildUrl(base, path, params?) with a typed query object.

Show solution
function buildUrl(base: string, path: string, params: Record<string, string | number> = {}): string {
  const url = new URL(path, base);
  for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v));
  return url.toString();
}
console.log(buildUrl('https://shop.test', '/search', { q: 'mouse', page: 2 }));

Output

https://shop.test/search?q=mouse&page=2

Explanation: a Record type keeps query values to strings or numbers, and URL encodes them.

23. Retry wrapper with genericsReal-world

Write retry&lt;T&gt;(fn, attempts) that returns the result of a successful attempt.

Show solution
function retry<T>(fn: (attempt: number) => T, attempts: number): T {
  let lastError: unknown;
  for (let i = 1; i <= attempts; i++) {
    try {
      return fn(i);
    } catch (e) {
      lastError = e;
      console.log(`attempt ${i} failed`);
    }
  }
  throw lastError;
}
const value = retry(attempt => {
  if (attempt < 3) throw new Error('not ready');
  return `ready on attempt ${attempt}`;
}, 5);
console.log(value);

Output

attempt 1 failed
attempt 2 failed
ready on attempt 3

Explanation: the generic return type means retry returns exactly what the wrapped function returns.

24. Async retry with delayReal-world

Write an async retry helper for flaky API calls.

Show solution
const sleep = (ms: number): Promise<void> => new Promise(r => setTimeout(r, ms));
async function retryAsync<T>(fn: () => Promise<T>, attempts: number, delayMs: number): Promise<T> {
  for (let i = 1; ; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i >= attempts) throw e;
      console.log(`retry ${i}: ${e instanceof Error ? e.message : e}`);
      await sleep(delayMs);
    }
  }
}
let calls = 0;
const data = await retryAsync(async () => {
  if (++calls < 3) throw new Error('503');
  return { items: 3 };
}, 4, 10);
console.log('items:', data.items);

Output

retry 1: 503
retry 2: 503
items: 3

Explanation: return await inside try lets rejections reach catch. The generic T keeps the result typed.

25. Duration formatterReal-world

Format milliseconds into a readable duration.

Show solution
function formatDuration(ms: number): string {
  if (ms < 1000) return `${ms} ms`;
  if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
  const m = Math.floor(ms / 60_000);
  const s = Math.round((ms % 60_000) / 1000);
  return `${m}m ${s}s`;
}
console.log([850, 2500, 125_000].map(formatDuration).join(' | '));

Output

850 ms | 2.5 s | 2m 5s

Explanation: one typed formatter keeps reports consistent. Numeric separators such as 60_000 improve readability.

26. Validation returning a result typeReal-world

Validate a signup form and return a typed result.

Show solution
type Signup = { email: string; password: string; age: number };
type Validation = { valid: true } | { valid: false; errors: string[] };
function validate(form: Signup): Validation {
  const errors: string[] = [];
  if (!form.email.includes('@')) errors.push('invalid email');
  if (form.password.length < 8) errors.push('password too short');
  if (form.age < 18) errors.push('must be 18+');
  return errors.length ? { valid: false, errors } : { valid: true };
}
for (const f of [{ email: 'qa@test.com', password: 'Secret123', age: 30 }, { email: 'qa', password: '123', age: 16 }]) {
  const r = validate(f);
  console.log(r.valid ? 'valid' : r.errors.join(', '));
}

Output

valid
invalid email, password too short, must be 18+

Explanation: the union result type forces callers to check valid before reading errors.

27. Data builder with PartialReal-world

Write buildUser(overrides: Partial&lt;User&gt;) for test data.

Show solution
interface User { name: string; email: string; role: 'admin' | 'viewer'; active: boolean }
function buildUser(overrides: Partial<User> = {}): User {
  return { name: 'QA User', email: 'qa.user@example.com', role: 'viewer', active: true, ...overrides };
}
const admin = buildUser({ role: 'admin', name: 'Admin' });
console.log(admin.name, admin.role, admin.active);

Output

Admin admin true

Explanation: Partial&lt;User&gt; lets each test override only the fields it cares about, while the result is always a complete User.

28. Page-object style functionsReal-world

Write a typed factory that returns login page actions.

Show solution
interface LoginPage {
  fill(field: 'email' | 'password', value: string): LoginPage;
  submit(): LoginPage;
  log(): string;
}
function createLoginPage(): LoginPage {
  const actions: string[] = [];
  const page: LoginPage = {
    fill(field, value) { actions.push(`fill ${field}=${field === 'password' ? '***' : value}`); return page; },
    submit() { actions.push('submit'); return page; },
    log() { return actions.join(' -> '); }
  };
  return page;
}
console.log(createLoginPage().fill('email', 'qa@test.com').fill('password', 'secret').submit().log());

Output

fill email=qa@test.com -> fill password=*** -> submit

Explanation: the interface types the chainable methods, and field only accepts the two known field names.

29. Debounce with genericsReal-world

Write a typed debounce for a search handler.

Show solution
function debounce<A extends unknown[]>(fn: (...args: A) => void, ms: number): (...args: A) => void {
  let timer: ReturnType<typeof setTimeout> | undefined;
  return (...args: A) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
const search = debounce((term: string) => console.log('search:', term), 20);
search('p'); search('pla'); search('playwright');
await new Promise(r => setTimeout(r, 50));

Output

search: playwright

Explanation: the generic A preserves the wrapped function’s parameter types, so search(123) would be a compile error.

30. Compose functionsReal-world

Combine string transformers into a slug function.

Show solution
type Transform = (s: string) => string;
const pipe = (...fns: Transform[]): Transform => input => fns.reduce((acc, fn) => fn(acc), input);
const slugify = pipe(s => s.trim(), s => s.toLowerCase(), s => s.replace(/[^a-z0-9]+/g, '-'), s => s.replace(/^-|-$/g, ''));
console.log(slugify('  Playwright: Getting Started!  '));

Output

playwright-getting-started

Explanation: small typed transforms combine into a pipeline that is easy to test step by step.

31. Typed event handlers mapReal-world

Map test events to typed handler functions.

Show solution
type TestEvent = 'start' | 'pass' | 'fail';
const handlers: Record<TestEvent, (name: string) => string> = {
  start: n => `▶ ${n}`,
  pass: n => `✔ ${n}`,
  fail: n => `✘ ${n}`
};
const events: [TestEvent, string][] = [['start', 'login'], ['pass', 'login'], ['start', 'cart'], ['fail', 'cart']];
for (const [event, name] of events) console.log(handlers[event](name));

Output

▶ login
✔ login
▶ cart
✘ cart

Explanation: a Record of functions requires a handler for every event, and each handler has the same signature.

Keep Practising

TypeScript Loops Practice Programs with Solutions (30 Programs)

Practise TypeScript loops with 30 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Loops lesson first.

TypeScript Beginner Programs

1. Sum 1 to n with a typed for loopBeginner

Write sumTo(n: number): number using a for loop.

Show solution
function sumTo(n: number): number {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
}
console.log(sumTo(10), sumTo(100));

Output

55 5050

Explanation: the loop counter and accumulator are inferred as number, and the return type documents the result.

2. Loop over a typed arrayBeginner

Print each browser from a string[] with for...of.

Show solution
const browsers: string[] = ['chromium', 'firefox', 'webkit'];
for (const browser of browsers) {
  console.log(`Run on ${browser.toUpperCase()}`);
}

Output

Run on CHROMIUM
Run on FIREFOX
Run on WEBKIT

Explanation: for...of infers the item type, here string, so string methods are available.

3. Countdown with whileBeginner

Count down from 3 to 1 with a while loop.

Show solution
let remaining: number = 3;
while (remaining > 0) {
  console.log(remaining);
  remaining--;
}
console.log('Liftoff');

Output

3
2
1
Liftoff

Explanation: a while loop repeats while its condition is true. Update the variable so it ends.

4. Multiplication tableBeginner

Print the 5 times table with a typed helper.

Show solution
function tableLine(n: number, i: number): string {
  return `${n} x ${i} = ${n * i}`;
}
for (let i = 1; i <= 5; i++) console.log(tableLine(5, i));

Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25

Explanation: a small typed helper keeps the loop body short and the formatting reusable.

5. Index and value with entriesBeginner

Print numbered test steps using entries().

Show solution
const steps: string[] = ['open page', 'login', 'add to cart'];
for (const [i, step] of steps.entries()) console.log(`${i + 1}. ${step}`);

Output

1. open page
2. login
3. add to cart

Explanation: entries() yields typed [number, string] pairs that destructure cleanly.

6. Loop over object keys safelyBeginner

Print a typed config with Object.entries.

Show solution
const config: Record<string, string | number> = { browser: 'chromium', workers: 4, retries: 1 };
for (const [key, value] of Object.entries(config)) console.log(`${key}=${value}`);

Output

browser=chromium
workers=4
retries=1

Explanation: Object.entries returns [string, value][], which avoids the indexing errors you get with for...in.

7. Even numbers into a typed arrayBeginner

Collect even numbers up to 12 into a number[].

Show solution
const evens: number[] = [];
for (let n = 2; n <= 12; n += 2) evens.push(n);
console.log(evens.join(', '));

Output

2, 4, 6, 8, 10, 12

Explanation: the array’s type is declared up front, so only numbers can be pushed.

8. do…while for at least one attemptBeginner

Try an action at least once with do...while.

Show solution
let attempt: number = 0;
let success: boolean = false;
do {
  attempt++;
  success = attempt >= 2;
  console.log(`attempt ${attempt}: ${success ? 'ok' : 'retry'}`);
} while (!success && attempt < 5);

Output

attempt 1: retry
attempt 2: ok

Explanation: do...while checks the condition after the body, so the action always runs once.

9. Characters of a stringBeginner

Count uppercase letters in a string.

Show solution
const text: string = 'Playwright Test Runner';
let upper = 0;
for (const ch of text) if (ch >= 'A' && ch <= 'Z') upper++;
console.log('Uppercase letters:', upper);

Output

Uppercase letters: 3

Explanation: strings are iterable, and each ch is typed as string.

10. break and continueBeginner

Print odd numbers below 10 and stop when a number above 7 is reached.

Show solution
const odd: number[] = [];
for (let i = 1; i < 10; i++) {
  if (i % 2 === 0) continue;
  if (i > 7) break;
  odd.push(i);
}
console.log(odd.join(' '));

Output

1 3 5 7

Explanation: continue skips even numbers and break leaves the loop once the limit is passed.

TypeScript Intermediate Programs

11. Loop over a union array with narrowingIntermediate

Sum the numbers in a mixed array and count the strings.

Show solution
const values: (number | string)[] = [10, 'ten', 20, 'twenty', 5];
let sum = 0, strings = 0;
for (const v of values) {
  if (typeof v === 'number') sum += v;
  else strings++;
}
console.log(`sum=${sum}, strings=${strings}`);

Output

sum=35, strings=2

Explanation: typeof narrows each item, so += is only used on numbers.

12. Loop over a typed object arrayIntermediate

Print users who are active, using an interface for the array items.

Show solution
interface User { name: string; active: boolean; role: 'admin' | 'viewer' }
const users: User[] = [
  { name: 'Asha', active: true, role: 'admin' },
  { name: 'Ravi', active: false, role: 'viewer' },
  { name: 'Meera', active: true, role: 'viewer' }
];
for (const u of users) {
  if (!u.active) continue;
  console.log(`${u.name} (${u.role})`);
}

Output

Asha (admin)
Meera (viewer)

Explanation: the interface gives every loop item a known shape, so property typos are compile errors.

13. Typed accumulator with RecordIntermediate

Count statuses into a Record&lt;Status, number&gt;.

Show solution
type Status = 'passed' | 'failed' | 'skipped';
const results: Status[] = ['passed', 'failed', 'passed', 'skipped', 'passed'];
const counts: Record<Status, number> = { passed: 0, failed: 0, skipped: 0 };
for (const r of results) counts[r]++;
console.log(counts);

Output

{ passed: 3, failed: 1, skipped: 1 }

Explanation: the record type guarantees a counter exists for every status.

14. Nested loops for combinationsIntermediate

Build every browser and viewport combination.

Show solution
const browsers: string[] = ['chromium', 'webkit'];
const viewports: [number, number][] = [[1280, 720], [375, 812]];
const combos: string[] = [];
for (const b of browsers) {
  for (const [w, h] of viewports) combos.push(`${b}@${w}x${h}`);
}
console.log(combos.join(', '));

Output

chromium@1280x720, chromium@375x812, webkit@1280x720, webkit@375x812

Explanation: tuple types make it clear each viewport has exactly a width and a height.

15. Labeled breakIntermediate

Find the first cell with a negative value in a grid.

Show solution
const grid: number[][] = [[3, 5, 2], [7, -1, 4], [-6, 8, 9]];
let found: [number, number] | null = null;
search: for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    if (grid[r][c] < 0) {
      found = [r, c];
      break search;
    }
  }
}
console.log(found);

Output

[ 1, 1 ]

Explanation: the label lets break exit both loops at once. The result type allows null when nothing is found.

16. Loop with a type guardIntermediate

Collect only valid emails from unknown input.

Show solution
const isString = (v: unknown): v is string => typeof v === 'string';
const input: unknown[] = ['qa@test.com', 42, 'bad-email', null, 'dev@shop.in'];
const emails: string[] = [];
for (const v of input) {
  if (isString(v) && v.includes('@')) emails.push(v);
}
console.log(emails.join(', '));

Output

qa@test.com, dev@shop.in

Explanation: the type guard narrows unknown to string, so includes is allowed.

17. Fibonacci into a typed arrayIntermediate

Generate the first 10 Fibonacci numbers.

Show solution
function fibonacci(count: number): number[] {
  const seq: number[] = [0, 1];
  while (seq.length < count) seq.push(seq[seq.length - 1] + seq[seq.length - 2]);
  return seq.slice(0, count);
}
console.log(fibonacci(10).join(' '));

Output

0 1 1 2 3 5 8 13 21 34

Explanation: the return type number[] documents the result, and slice handles counts below 2.

18. Prime numbers up to nIntermediate

Return all primes up to 30.

Show solution
function primesUpTo(n: number): number[] {
  const primes: number[] = [];
  for (let i = 2; i <= n; i++) {
    let isPrime = true;
    for (const p of primes) {
      if (p * p > i) break;
      if (i % p === 0) { isPrime = false; break; }
    }
    if (isPrime) primes.push(i);
  }
  return primes;
}
console.log(primesUpTo(30).join(' '));

Output

2 3 5 7 11 13 17 19 23 29

Explanation: dividing only by primes up to √i keeps the inner loop short.

19. Iterate a MapIntermediate

Loop over a Map&lt;string, number&gt; of response times.

Show solution
const timings = new Map<string, number>([['/login', 220], ['/cart', 480], ['/search', 130]]);
let slowest: [string, number] = ['', 0];
for (const [url, ms] of timings) {
  if (ms > slowest[1]) slowest = [url, ms];
}
console.log(`Slowest: ${slowest[0]} (${slowest[1]} ms)`);

Output

Slowest: /cart (480 ms)

Explanation: iterating a Map yields typed [key, value] pairs.

20. Reverse a string with a loopIntermediate

Reverse a string without using reverse().

Show solution
function reverse(text: string): string {
  let out = '';
  for (let i = text.length - 1; i >= 0; i--) out += text[i];
  return out;
}
console.log(reverse('TypeScript'));

Output

tpircSepyT

Explanation: counting down from the last index visits characters in reverse order.

TypeScript Real-World QA Scenario Programs

21. Retry until successReal-world

Retry a typed action until it succeeds or the attempts run out.

Show solution
type ActionResult = { ok: boolean; message: string };
let calls = 0;
const clickPay = (): ActionResult => (++calls < 3 ? { ok: false, message: 'button disabled' } : { ok: true, message: 'paid' });
const MAX = 5;
let result: ActionResult = { ok: false, message: 'not started' };
for (let attempt = 1; attempt <= MAX && !result.ok; attempt++) {
  result = clickPay();
  console.log(`attempt ${attempt}: ${result.message}`);
}

Output

attempt 1: button disabled
attempt 2: button disabled
attempt 3: paid

Explanation: the loop condition combines the attempt limit and the success flag, so it stops as soon as either is reached.

22. Poll a job statusReal-world

Poll a typed status sequence until it is done or failed.

Show solution
type JobStatus = 'queued' | 'running' | 'done' | 'failed';
const sequence: JobStatus[] = ['queued', 'running', 'running', 'done'];
let poll = 0;
let status: JobStatus = 'queued';
while (status !== 'done' && status !== 'failed' && poll < sequence.length) {
  status = sequence[poll++];
  console.log(`poll ${poll}: ${status}`);
}

Output

poll 1: queued
poll 2: running
poll 3: running
poll 4: done

Explanation: the literal union makes the stop conditions explicit and typo-proof.

23. Summarise test resultsReal-world

Calculate pass rate and total duration from typed results.

Show solution
interface TestResult { title: string; status: 'passed' | 'failed'; ms: number }
const results: TestResult[] = [
  { title: 'login', status: 'passed', ms: 1200 },
  { title: 'search', status: 'failed', ms: 3400 },
  { title: 'checkout', status: 'passed', ms: 5100 }
];
let passed = 0, totalMs = 0;
for (const r of results) {
  if (r.status === 'passed') passed++;
  totalMs += r.ms;
}
console.log(`${passed}/${results.length} passed in ${(totalMs / 1000).toFixed(1)}s`);

Output

2/3 passed in 9.7s

Explanation: a single typed loop gathers several statistics at once.

24. Find the first failureReal-world

Return the first failed test or undefined.

Show solution
interface Run { name: string; passed: boolean }
function firstFailure(runs: Run[]): Run | undefined {
  for (const run of runs) if (!run.passed) return run;
  return undefined;
}
const runs: Run[] = [{ name: 'login', passed: true }, { name: 'cart', passed: false }];
console.log(firstFailure(runs)?.name ?? 'all passed');
console.log(firstFailure([{ name: 'login', passed: true }])?.name ?? 'all passed');

Output

cart
all passed

Explanation: returning inside the loop stops at the first match. The | undefined return type forces callers to handle “not found”.

25. Cart total from typed itemsReal-world

Calculate a cart total and the most expensive line.

Show solution
interface CartLine { sku: string; price: number; qty: number }
const cart: CartLine[] = [{ sku: 'KB', price: 1499, qty: 1 }, { sku: 'MS', price: 599, qty: 2 }, { sku: 'CB', price: 199, qty: 3 }];
let total = 0;
let top: CartLine = cart[0];
for (const line of cart) {
  total += line.price * line.qty;
  if (line.price * line.qty > top.price * top.qty) top = line;
}
console.log('Total:', total, '| Biggest line:', top.sku);

Output

Total: 3294 | Biggest line: KB

Explanation: typed lines guarantee numeric prices and quantities for the arithmetic.

26. Generate typed test usersReal-world

Generate a list of typed test users with a counter loop.

Show solution
interface TestUser { id: number; email: string; role: 'admin' | 'viewer' }
const users: TestUser[] = [];
for (let i = 1; i <= 4; i++) {
  users.push({ id: i, email: `qa${i}@example.com`, role: i === 1 ? 'admin' : 'viewer' });
}
console.log(users.map(u => `${u.id}:${u.role}`).join(' '));

Output

1:admin 2:viewer 3:viewer 4:viewer

Explanation: pushing objects into a typed array checks each one against the interface.

27. Validate every form fieldReal-world

Loop over typed field rules and collect validation errors.

Show solution
interface Rule { field: string; value: string; minLength: number }
const rules: Rule[] = [
  { field: 'username', value: 'qa', minLength: 3 },
  { field: 'password', value: 'Secret123', minLength: 8 },
  { field: 'city', value: '', minLength: 1 }
];
const errors: string[] = [];
for (const r of rules) {
  if (r.value.trim().length < r.minLength) errors.push(`${r.field} needs ${r.minLength}+ characters`);
}
console.log(errors.length ? errors.join('; ') : 'All valid');

Output

username needs 3+ characters; city needs 1+ characters

Explanation: data-driven rules keep validation logic in one loop instead of repeated if blocks.

28. Paginate until an empty pageReal-world

Read typed pages until the API returns an empty list.

Show solution
const pages: string[][] = [['a', 'b'], ['c', 'd'], ['e'], []];
let page = 0;
const all: string[] = [];
while (true) {
  const items = pages[page];
  if (items.length === 0) break;
  all.push(...items);
  page++;
}
console.log(`${page} pages, ${all.length} items: ${all.join('')}`);

Output

3 pages, 5 items: abcde

Explanation: while (true) with a clear break condition is a common pattern for pagination.

29. Compare expected and actual listsReal-world

Report missing and unexpected menu items with typed arrays.

Show solution
const expected: readonly string[] = ['Home', 'Shop', 'Blog', 'Contact'];
const actual: string[] = ['Home', 'Shop', 'Offers', 'Contact'];
const missing: string[] = [];
const extra: string[] = [];
for (const item of expected) if (!actual.includes(item)) missing.push(item);
for (const item of actual) if (!expected.includes(item)) extra.push(item);
console.log('missing:', missing.join(', ') || '-', '| extra:', extra.join(', ') || '-');

Output

missing: Blog | extra: Offers

Explanation: two simple loops produce a clear diff, which is easier to debug than a single equality check.

30. Run async steps in orderReal-world

Run typed async steps sequentially with for...of and await.

Show solution
type Step = { name: string; ms: number };
const sleep = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
const steps: Step[] = [{ name: 'open', ms: 20 }, { name: 'fill', ms: 5 }, { name: 'submit', ms: 10 }];
const done: string[] = [];
for (const step of steps) {
  await sleep(step.ms);
  done.push(step.name);
}
console.log(done.join(' -> '));

Output

open -> fill -> submit

Explanation: await inside for...of keeps the steps in order, the same way Playwright actions run one after another.

Keep Practising

TypeScript Conditions Practice Programs with Solutions (30 Programs)

Practise TypeScript conditions and narrowing with 30 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Conditions lesson first.

TypeScript Beginner Programs

1. Positive, negative or zeroBeginner

Write sign(n: number) that returns 'positive', 'negative' or 'zero'.

Show solution
type Sign = 'positive' | 'negative' | 'zero';
function sign(n: number): Sign {
  if (n > 0) return 'positive';
  if (n < 0) return 'negative';
  return 'zero';
}
console.log(sign(7), sign(-2), sign(0));

Output

positive negative zero

Explanation: the return type is a literal union, so every branch must return one of the allowed strings.

2. Pass or failBeginner

Return 'PASS' when a score is at least 60, otherwise 'FAIL'.

Show solution
function result(score: number): 'PASS' | 'FAIL' {
  if (score >= 60) {
    return 'PASS';
  } else {
    return 'FAIL';
  }
}
console.log(result(72), result(45));

Output

PASS FAIL

Explanation: if/else picks one of two outcomes. The return type documents both possibilities.

3. Grade bandsBeginner

Convert marks into grades A, B, C or F with an else if chain.

Show solution
type Grade = 'A' | 'B' | 'C' | 'F';
function grade(marks: number): Grade {
  if (marks >= 90) return 'A';
  else if (marks >= 75) return 'B';
  else if (marks >= 60) return 'C';
  else return 'F';
}
console.log([95, 80, 61, 30].map(grade).join(' '));

Output

A B C F

Explanation: checking the highest threshold first ensures each value lands in the right band.

4. Leap yearBeginner

Write isLeapYear(year: number): boolean and test three years.

Show solution
function isLeapYear(year: number): boolean {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
for (const y of [2024, 1900, 2000]) console.log(y, isLeapYear(y));

Output

2024 true
1900 false
2000 true

Explanation: the whole condition is a boolean expression, so it can be returned directly.

5. switch on a string unionBeginner

Map a day name to a working-day flag with switch.

Show solution
type Day = 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat' | 'Sun';
function isWorkingDay(day: Day): boolean {
  switch (day) {
    case 'Sat':
    case 'Sun':
      return false;
    default:
      return true;
  }
}
console.log(isWorkingDay('Mon'), isWorkingDay('Sun'));

Output

true false

Explanation: TypeScript checks that each case is a member of the Day union, so typos are caught.

6. Ternary with typesBeginner

Choose a label with a ternary and store it in a typed variable.

Show solution
const itemCount: number = 1;
const label: string = itemCount === 1 ? 'item' : 'items';
console.log(`${itemCount} ${label}`);

Output

1 item

Explanation: both branches return strings, so the result type is string.

7. Handle a nullable valueBeginner

Print a greeting when a name is present, otherwise a default message.

Show solution
function greet(name: string | null): string {
  if (name === null) return 'Hello, guest';
  return `Hello, ${name.toUpperCase()}`;
}
console.log(greet('asha'));
console.log(greet(null));

Output

Hello, ASHA
Hello, guest

Explanation: after the null check, TypeScript narrows name to string, so toUpperCase is allowed.

8. Optional parameter checkBeginner

Use a default when an optional parameter is missing.

Show solution
function openPage(path: string, timeout?: number): string {
  if (timeout === undefined) return `${path} (default timeout)`;
  return `${path} (${timeout} ms)`;
}
console.log(openPage('/login'));
console.log(openPage('/reports', 60000));

Output

/login (default timeout)
/reports (60000 ms)

Explanation: an optional parameter has type number | undefined, so you check for undefined before using it.

9. Truthiness narrowingBeginner

Print the length of a string only when it is non-empty.

Show solution
function describe(text?: string): string {
  if (text) return `${text.length} characters`;
  return 'empty or missing';
}
console.log(describe('Playwright'), '|', describe(''), '|', describe());

Output

10 characters | empty or missing | empty or missing

Explanation: if (text) removes undefined and also skips the empty string, which is falsy.

10. Largest of threeBeginner

Return the largest of three numbers with if conditions.

Show solution
function largest(a: number, b: number, c: number): number {
  if (a >= b && a >= c) return a;
  if (b >= c) return b;
  return c;
}
console.log(largest(12, 45, 30), largest(9, 3, 9));

Output

45 9

Explanation: once a is ruled out, only b and c remain to be compared.

TypeScript Intermediate Programs

11. typeof narrowingIntermediate

Format an input that may be a number, string or boolean.

Show solution
function format(value: number | string | boolean): string {
  if (typeof value === 'number') return value.toFixed(1);
  if (typeof value === 'boolean') return value ? 'yes' : 'no';
  return value.trim();
}
console.log(format(3.14159), format(true), format('  ok  '));

Output

3.1 yes ok

Explanation: each typeof check narrows the union, and the final return knows only string is left.

12. Discriminated union with ifIntermediate

Handle API responses that are either success or error.

Show solution
type Res = { status: 'ok'; data: string[] } | { status: 'error'; message: string };
function handle(res: Res): string {
  if (res.status === 'ok') return `Loaded ${res.data.length} rows`;
  return `Error: ${res.message}`;
}
console.log(handle({ status: 'ok', data: ['a', 'b'] }));
console.log(handle({ status: 'error', message: 'Unauthorized' }));

Output

Loaded 2 rows
Error: Unauthorized

Explanation: checking the shared status field narrows to the matching member of the union.

13. Exhaustive switch with neverIntermediate

Map test outcomes to symbols and make the compiler check every case.

Show solution
type Outcome = 'passed' | 'failed' | 'skipped' | 'flaky';
function symbol(o: Outcome): string {
  switch (o) {
    case 'passed': return '✔';
    case 'failed': return '✘';
    case 'skipped': return '○';
    case 'flaky': return '≈';
    default: {
      const unhandled: never = o;
      throw new Error(`Unhandled outcome: ${unhandled}`);
    }
  }
}
console.log((['passed', 'flaky', 'failed'] as Outcome[]).map(symbol).join(' '));

Output

✔ ≈ ✘

Explanation: adding a new outcome without a case makes the never assignment fail to compile.

14. in operator narrowingIntermediate

Tell a Card payment from a Upi payment.

Show solution
type Card = { cardNumber: string; expiry: string };
type Upi = { upiId: string };
function paymentLabel(p: Card | Upi): string {
  if ('cardNumber' in p) return `Card ending ${p.cardNumber.slice(-4)}`;
  return `UPI ${p.upiId}`;
}
console.log(paymentLabel({ cardNumber: '4111111111111234', expiry: '12/28' }));
console.log(paymentLabel({ upiId: 'qa@bank' }));

Output

Card ending 1234
UPI qa@bank

Explanation: checking for a property with in narrows a union of object types.

15. instanceof narrowingIntermediate

Handle a caught error safely, whatever was thrown.

Show solution
function message(err: unknown): string {
  if (err instanceof Error) return err.message;
  if (typeof err === 'string') return err;
  return 'Unknown error';
}
console.log(message(new Error('Timeout')), '|', message('Network down'), '|', message(42));

Output

Timeout | Network down | Unknown error

Explanation: in strict mode a caught error is unknown, so narrow it before reading message.

16. Custom type guardIntermediate

Write isNumberArray and use it in a condition.

Show solution
function isNumberArray(value: unknown): value is number[] {
  return Array.isArray(value) && value.every(v => typeof v === 'number');
}
for (const input of [[1, 2, 3], ['1', 2], 'x'] as unknown[]) {
  if (isNumberArray(input)) console.log('sum', input.reduce((a, b) => a + b, 0));
  else console.log('not a number array');
}

Output

sum 6
not a number array
not a number array

Explanation: the value is number[] return type narrows the variable in the if branch.

17. Equality narrowingIntermediate

Narrow two union-typed values by comparing them.

Show solution
function compare(a: string | number, b: string | boolean): string {
  if (a === b) return `both are the string "${a.toUpperCase()}"`;
  return 'different';
}
console.log(compare('qa', 'qa'));
console.log(compare(1, true));

Output

both are the string "QA"
different

Explanation: if a === b, both must be strings (the only shared type), so toUpperCase is allowed.

18. Lookup object instead of switchIntermediate

Map HTTP status codes to messages with a typed record and a default.

Show solution
const STATUS_TEXT: Record<number, string> = { 200: 'OK', 201: 'Created', 404: 'Not Found', 500: 'Server Error' };
function statusText(code: number): string {
  return STATUS_TEXT[code] ?? 'Unknown';
}
console.log([200, 404, 418].map(statusText).join(', '));

Output

OK, Not Found, Unknown

Explanation: a lookup table replaces long switch statements. ?? supplies the default.

19. Guard clauses with typesIntermediate

Validate an age value with early returns.

Show solution
function validateAge(age: unknown): string {
  if (typeof age !== 'number') return 'Age must be a number';
  if (!Number.isInteger(age)) return 'Age must be a whole number';
  if (age < 18) return 'Must be 18 or older';
  return 'Valid';
}
console.log([25, '25', 17.5, 16].map(validateAge).join(' | '));

Output

Valid | Age must be a number | Age must be a whole number | Must be 18 or older

Explanation: after the first guard, age is a number for all the following checks.

20. Assertion functionIntermediate

Write an assertDefined function that narrows a value after it runs.

Show solution
function assertDefined<T>(value: T | undefined, name: string): asserts value is T {
  if (value === undefined) throw new Error(`${name} is required`);
}
const env: Record<string, string | undefined> = { BASE_URL: 'https://qa.app.test' };
const baseUrl = env.BASE_URL;
assertDefined(baseUrl, 'BASE_URL');
console.log(baseUrl.toUpperCase());
try {
  assertDefined(env.TOKEN, 'TOKEN');
} catch (e) {
  console.log(e instanceof Error ? e.message : e);
}

Output

HTTPS://QA.APP.TEST
TOKEN is required

Explanation: asserts value is T tells TypeScript the value is defined after the call, like expect(...).toBeDefined() combined with type narrowing.

TypeScript Real-World QA Scenario Programs

21. Shipping cost rulesReal-world

Calculate shipping with typed thresholds, then test the boundary values.

Show solution
const FREE_ABOVE = 999, MID_FROM = 500;
function shipping(total: number): number {
  if (total > FREE_ABOVE) return 0;
  if (total >= MID_FROM) return 49;
  return 99;
}
for (const t of [499, 500, 999, 1000]) console.log(t, shipping(t));

Output

499 99
500 49
999 49
1000 0

Explanation: boundary values (499, 500, 999, 1000) are where off-by-one bugs appear, so test them explicitly.

22. Environment selectionReal-world

Choose a base URL from an environment name with an exhaustive switch.

Show solution
type Env = 'dev' | 'qa' | 'prod';
function baseUrl(env: Env): string {
  switch (env) {
    case 'dev': return 'http://localhost:3000';
    case 'qa': return 'https://qa.shop.test';
    case 'prod': return 'https://shop.test';
  }
}
console.log(baseUrl('qa'));

Output

https://qa.shop.test

Explanation: because every Env member returns, TypeScript knows the function never falls through without a value.

23. Password strength rulesReal-world

Return the first failing password rule, or 'Strong'.

Show solution
function passwordIssue(pw: string): string {
  if (pw.length < 8) return 'Too short';
  if (!/[A-Z]/.test(pw)) return 'Needs an uppercase letter';
  if (!/\d/.test(pw)) return 'Needs a digit';
  if (!/[^A-Za-z0-9]/.test(pw)) return 'Needs a symbol';
  return 'Strong';
}
for (const pw of ['abc', 'abcdefgh', 'Abcdefgh', 'Abcdefg1', 'Abcdef1!']) console.log(pw, '->', passwordIssue(pw));

Output

abc -> Too short
abcdefgh -> Needs an uppercase letter
Abcdefgh -> Needs a digit
Abcdefg1 -> Needs a symbol
Abcdef1! -> Strong

Explanation: ordered guard clauses mirror the order in which a form shows validation messages.

24. Classify an API responseReal-world

Classify typed responses into success, client error or server error.

Show solution
type ApiResponse = { status: number; body?: { items: string[] } };
function classify(r: ApiResponse): string {
  if (r.status >= 500) return 'server error';
  if (r.status >= 400) return 'client error';
  if (!r.body || r.body.items.length === 0) return 'success (empty)';
  const n = r.body.items.length;
  return `success (${n} item${n === 1 ? '' : 's'})`;
}
const responses: ApiResponse[] = [{ status: 200, body: { items: ['a'] } }, { status: 200 }, { status: 404 }, { status: 503 }];
for (const r of responses) console.log(r.status, classify(r));

Output

200 success (1 item)
200 success (empty)
404 client error
503 server error

Explanation: checking error statuses first and body before items keeps every access type-safe.

25. Feature access by planReal-world

Decide whether a plan can use a feature.

Show solution
type Plan = 'free' | 'pro' | 'enterprise';
type Feature = 'reports' | 'sso' | 'export';
function canUse(plan: Plan, feature: Feature): boolean {
  if (feature === 'sso') return plan === 'enterprise';
  if (feature === 'reports') return plan !== 'free';
  return true;
}
for (const plan of ['free', 'pro', 'enterprise'] as Plan[]) {
  console.log(plan, canUse(plan, 'reports'), canUse(plan, 'sso'), canUse(plan, 'export'));
}

Output

free false false true
pro true false true
enterprise true true true

Explanation: literal unions for both inputs make invalid plan or feature names a compile error.

26. Test priority triageReal-world

Assign P1, P2 or P3 to typed test cases.

Show solution
type TestCase = { id: string; area: string; blocker: boolean; regression: boolean };
type Priority = 'P1' | 'P2' | 'P3';
function priority(t: TestCase): Priority {
  if (t.area === 'checkout' || t.blocker) return 'P1';
  if (t.regression) return 'P2';
  return 'P3';
}
const tests: TestCase[] = [
  { id: 'TC1', area: 'checkout', blocker: false, regression: true },
  { id: 'TC2', area: 'search', blocker: false, regression: true },
  { id: 'TC3', area: 'help', blocker: false, regression: false }
];
console.log(tests.map(t => `${t.id}:${priority(t)}`).join(' '));

Output

TC1:P1 TC2:P2 TC3:P3

Explanation: the rule reads like the written triage policy, and the types document the inputs.

27. Flaky test classificationReal-world

Classify a test from its pass count over a number of runs.

Show solution
type Stability = 'stable' | 'flaky' | 'broken';
function stability(passes: number, runs: number): Stability {
  if (passes === runs) return 'stable';
  if (passes === 0) return 'broken';
  return 'flaky';
}
for (const [p, r] of [[10, 10], [7, 10], [0, 10]] as [number, number][]) console.log(`${p}/${r}`, stability(p, r));

Output

10/10 stable
7/10 flaky
0/10 broken

Explanation: the typed tuple array makes it clear each entry is a pair of numbers.

28. Retry decisionReal-world

Retry only on server errors or 429, while attempts remain.

Show solution
type Attempt = { status: number; attempt: number };
const MAX_ATTEMPTS = 3;
function shouldRetry({ status, attempt }: Attempt): boolean {
  if (attempt >= MAX_ATTEMPTS) return false;
  return status >= 500 || status === 429;
}
const cases: Attempt[] = [{ status: 503, attempt: 1 }, { status: 404, attempt: 1 }, { status: 429, attempt: 3 }];
for (const c of cases) console.log(c.status, c.attempt, shouldRetry(c));

Output

503 1 true
404 1 false
429 3 false

Explanation: a guard clause handles the attempt limit first, so the status rule stays simple.

29. Weekend scheduling checkReal-world

Skip weekend dates when scheduling a nightly run, using UTC days.

Show solution
function shouldRun(isoDate: string): boolean {
  const day = new Date(`${isoDate}T00:00:00Z`).getUTCDay();
  return day !== 0 && day !== 6;
}
for (const d of ['2026-11-06', '2026-11-07', '2026-11-09']) console.log(d, shouldRun(d) ? 'run' : 'skip');

Output

2026-11-06 run
2026-11-07 skip
2026-11-09 run

Explanation: getUTCDay() returns 0 for Sunday and 6 for Saturday, independent of the machine’s time zone.

30. Locator choice by available attributesReal-world

Pick the best locator strategy from what an element provides.

Show solution
type ElementInfo = { role?: string; name?: string; testId?: string; css: string };
function bestLocator(el: ElementInfo): string {
  if (el.role && el.name) return `getByRole('${el.role}', { name: '${el.name}' })`;
  if (el.testId) return `getByTestId('${el.testId}')`;
  return `locator('${el.css}')`;
}
console.log(bestLocator({ role: 'button', name: 'Pay', css: '.btn' }));
console.log(bestLocator({ testId: 'cart-total', css: '#total' }));
console.log(bestLocator({ css: 'div > span:nth-child(2)' }));

Output

getByRole('button', { name: 'Pay' })
getByTestId('cart-total')
locator('div > span:nth-child(2)')

Explanation: conditions encode Playwright’s locator priority: role and name first, then test ID, then CSS.

Keep Practising

TypeScript Operators Practice Programs with Solutions (30 Programs)

Practise TypeScript operators with 30 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Operators lesson first.

TypeScript Beginner Programs

1. Typed arithmeticBeginner

Write calculate(a, b) that returns the sum, difference, product and remainder as an object.

Show solution
function calculate(a: number, b: number): { sum: number; diff: number; product: number; rem: number } {
  return { sum: a + b, diff: a - b, product: a * b, rem: a % b };
}
console.log(calculate(17, 5));

Output

{ sum: 22, diff: 12, product: 85, rem: 2 }

Explanation: typed parameters guarantee both operands are numbers, so + always adds instead of concatenating.

2. Prevent string concatenation bugsBeginner

Show that a typed function rejects a numeric string argument.

Show solution
function addPrices(a: number, b: number): number {
  return a + b;
}
console.log(addPrices(499, 1299));
// @ts-expect-error: Argument of type 'string' is not assignable to parameter of type 'number'
console.log(addPrices('499', 1299));

Output

1798
4991299

Explanation: in JavaScript '499' + 1299 gives '4991299'. TypeScript catches the wrong argument type before the code runs.

3. Comparison operators return booleanBeginner

Compare scores and store the results in boolean variables.

Show solution
const score: number = 72;
const passMark: number = 60;
const passed: boolean = score >= passMark;
const perfect: boolean = score === 100;
console.log(passed, perfect);

Output

true false

Explanation: comparison operators always produce boolean values.

4. Comparing unrelated types is an errorBeginner

Show that comparing a number with a string literal is flagged.

Show solution
const status: number = 200;
// @ts-expect-error: This comparison appears to be unintentional because the types have no overlap
const same = status === '200';
console.log(same, status === Number('200'));

Output

false true

Explanation: TypeScript reports comparisons that can never be true, a common bug when API values are strings.

5. Logical operators with booleansBeginner

Combine boolean flags with &amp;&amp;, || and !.

Show solution
const isLoggedIn: boolean = true;
const isAdmin: boolean = false;
const canEdit: boolean = isLoggedIn && isAdmin;
const canView: boolean = isLoggedIn || isAdmin;
console.log(canEdit, canView, !isAdmin);

Output

false true true

Explanation: logical operators combine conditions. With boolean operands they return booleans.

6. Increment and compound assignmentBeginner

Update a typed counter with ++, += and *=.

Show solution
let retries: number = 0;
retries++;
retries += 2;
retries *= 10;
console.log(retries);

Output

30

Explanation: compound operators keep the variable’s type, here number.

7. Ternary with typed resultBeginner

Return a literal union from a ternary expression.

Show solution
type Verdict = 'PASS' | 'FAIL';
const verdict = (score: number): Verdict => (score >= 60 ? 'PASS' : 'FAIL');
console.log(verdict(75), verdict(40));

Output

PASS FAIL

Explanation: both branches return members of the Verdict union, so the function’s return type is satisfied.

8. Nullish coalescing with typed defaultsBeginner

Use ?? to provide a default for an optional timeout.

Show solution
function getTimeout(custom?: number): number {
  return custom ?? 30000;
}
console.log(getTimeout(), getTimeout(0), getTimeout(5000));

Output

30000 0 5000

Explanation: ?? falls back only for undefined or null, so a valid 0 is kept. The result type is number.

9. Optional chainingBeginner

Safely read a nested optional property.

Show solution
type User = { name: string; address?: { city?: string } };
const users: User[] = [{ name: 'Asha', address: { city: 'Delhi' } }, { name: 'Ravi' }];
for (const u of users) console.log(u.name, u.address?.city ?? 'unknown');

Output

Asha Delhi
Ravi unknown

Explanation: ?. returns undefined when a link in the chain is missing, and TypeScript types the result as string | undefined.

10. Exponent and Math operationsBeginner

Calculate compound growth with **.

Show solution
const principal: number = 1000;
const rate: number = 0.1;
const years: number = 3;
const amount: number = principal * (1 + rate) ** years;
console.log(amount.toFixed(2));

Output

1331.00

Explanation: ** raises a number to a power, and the result type is number.

TypeScript Intermediate Programs

11. typeof narrowingIntermediate

Format a value that can be a number or a string.

Show solution
function format(value: number | string): string {
  if (typeof value === 'number') return value.toFixed(2);
  return value.trim().toUpperCase();
}
console.log(format(3.14159));
console.log(format('  passed '));

Output

3.14
PASSED

Explanation: after typeof value === 'number', TypeScript knows value is a number. In the other branch it must be a string.

12. in operator narrowingIntermediate

Distinguish two object shapes with the in operator.

Show solution
type ApiError = { error: string };
type ApiData = { data: number[] };
function describe(res: ApiError | ApiData): string {
  return 'error' in res ? `Error: ${res.error}` : `Data: ${res.data.length} items`;
}
console.log(describe({ error: 'Unauthorized' }));
console.log(describe({ data: [1, 2, 3] }));

Output

Error: Unauthorized
Data: 3 items

Explanation: checking for a property with in narrows a union of object types.

13. instanceof narrowingIntermediate

Handle a Date or a timestamp number.

Show solution
function toIso(value: Date | number): string {
  return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
console.log(toIso(new Date('2026-01-01T00:00:00Z')));
console.log(toIso(0));

Output

2026-01-01T00:00:00.000Z
1970-01-01T00:00:00.000Z

Explanation: instanceof narrows to a class type, so Date methods are allowed in that branch.

14. Non-null assertionIntermediate

Use ! when you know a value is not undefined, and compare it with a safe check.

Show solution
const roles = new Map<string, string>([['asha', 'admin']]);
const role: string = roles.get('asha')!;
console.log(role);
const maybe = roles.get('ravi');
console.log(maybe !== undefined ? maybe : 'no role');

Output

admin
no role

Explanation: ! removes undefined from the type without a runtime check. Prefer a real check when the value might be missing.

15. keyof operatorIntermediate

Read a property of a config object using a key typed with keyof.

Show solution
const config = { browser: 'chromium', workers: 4, headless: true };
type ConfigKey = keyof typeof config;
function read(key: ConfigKey) {
  return config[key];
}
console.log(read('workers'), read('browser'));
// @ts-expect-error: '"timeout"' is not assignable to parameter of type 'ConfigKey'
read('timeout');

Output

4 chromium

Explanation: keyof creates a union of property names, so only existing keys can be passed.

16. typeof type operatorIntermediate

Create a type from an existing value with typeof.

Show solution
const defaultUser = { name: 'qa', role: 'viewer' as 'viewer' | 'admin' };
type User = typeof defaultUser;
const admin: User = { name: 'boss', role: 'admin' };
console.log(admin.role);

Output

admin

Explanation: typeof value in a type position reuses the value’s type, so you do not repeat it by hand.

17. Indexed access typesIntermediate

Get the type of a nested property with indexed access.

Show solution
type Order = { id: number; customer: { name: string; tier: 'gold' | 'silver' } };
type Tier = Order['customer']['tier'];
const tiers: Tier[] = ['gold', 'silver', 'gold'];
console.log(tiers.filter(t => t === 'gold').length);

Output

2

Explanation: Type['prop'] looks up a property’s type, so related types stay in sync automatically.

18. satisfies operatorIntermediate

Check a config against a type while keeping its literal values.

Show solution
type Env = 'qa' | 'prod';
const urls = {
  qa: 'https://qa.app.test',
  prod: 'https://app.test'
} satisfies Record<Env, string>;
console.log(urls.qa.startsWith('https'), Object.keys(urls).length);

Output

true 2

Explanation: satisfies validates the shape without widening the type, so the compiler still knows the exact keys.

19. as const with operatorsIntermediate

Use a literal-typed array with includes and a type guard.

Show solution
const ROLES = ['admin', 'editor', 'viewer'] as const;
type Role = (typeof ROLES)[number];
const isRole = (value: string): value is Role => (ROLES as readonly string[]).includes(value);
for (const v of ['editor', 'guest']) console.log(v, isRole(v));

Output

editor true
guest false

Explanation: widening the array to readonly string[] lets includes accept any string, while the type guard narrows the result.

20. Bitwise flags with an enumIntermediate

Combine permission flags with | and test them with &amp;.

Show solution
enum Permission { Read = 1, Write = 2, Delete = 4 }
const userPerms: number = Permission.Read | Permission.Write;
const can = (p: Permission): boolean => (userPerms & p) !== 0;
console.log(can(Permission.Read), can(Permission.Write), can(Permission.Delete));

Output

true true false

Explanation: numeric enum values are numbers, so bitwise operators combine and test flags.

TypeScript Real-World QA Scenario Programs

21. Cart total with taxReal-world

Write a typed function that calculates a cart total with tax.

Show solution
type CartItem = { name: string; price: number; qty: number };
function cartTotal(items: CartItem[], taxRate: number): number {
  const subtotal = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  return Math.round(subtotal * (1 + taxRate) * 100) / 100;
}
console.log(cartTotal([{ name: 'Mouse', price: 599, qty: 2 }, { name: 'Pad', price: 299, qty: 1 }], 0.18));

Output

1766.46

Explanation: typed items guarantee price and qty are numbers, so the arithmetic is safe.

22. Pass rate with typed resultReal-world

Calculate a pass rate and return a typed status.

Show solution
type Health = 'green' | 'amber' | 'red';
function health(passed: number, total: number): { rate: number; status: Health } {
  const rate = total === 0 ? 0 : (passed / total) * 100;
  const status: Health = rate >= 95 ? 'green' : rate >= 80 ? 'amber' : 'red';
  return { rate: Number(rate.toFixed(1)), status };
}
console.log(health(97, 100), health(41, 50), health(5, 10));

Output

{ rate: 97, status: 'green' } { rate: 82, status: 'amber' } { rate: 50, status: 'red' }

Explanation: the return type documents the shape, and the guard total === 0 avoids dividing by zero.

23. Response time SLA checkReal-world

Check whether response times are within an SLA range.

Show solution
const SLA = { min: 0, max: 800 } as const;
const within = (ms: number): boolean => ms >= SLA.min && ms <= SLA.max;
const timings: number[] = [120, 950, 640];
for (const t of timings) console.log(`${t} ms`, within(t) ? 'OK' : 'BREACH');

Output

120 ms OK
950 ms BREACH
640 ms OK

Explanation: &amp;&amp; combines the two boundary checks, and the typed array guarantees numeric input.

24. Optional chaining on an API responseReal-world

Safely read the first item’s name from a response that may be empty.

Show solution
type Res = { data?: { items: { name: string }[] } };
const responses: Res[] = [{ data: { items: [{ name: 'Mouse' }] } }, { data: { items: [] } }, {}];
for (const r of responses) console.log(r.data?.items[0]?.name ?? 'no items');

Output

Mouse
no items
no items

Explanation: ?. on both data and items[0] prevents errors when either is missing.

25. Merge config with spreadReal-world

Merge typed default and override configs, letting overrides win.

Show solution
type Config = { baseURL: string; retries: number; headless: boolean };
const defaults: Config = { baseURL: 'http://localhost:3000', retries: 0, headless: true };
const overrides: Partial<Config> = { retries: 2, baseURL: 'https://qa.app.test' };
const finalConfig: Config = { ...defaults, ...overrides };
console.log(finalConfig);

Output

{ baseURL: 'https://qa.app.test', retries: 2, headless: true }

Explanation: Partial&lt;Config&gt; makes every property optional, and spreading it over the defaults produces a complete Config.

26. Type guard for API statusReal-world

Narrow a status code to success or failure with a type guard.

Show solution
type SuccessCode = 200 | 201 | 204;
const isSuccess = (code: number): code is SuccessCode => code === 200 || code === 201 || code === 204;
for (const code of [200, 204, 404, 500]) {
  console.log(code, isSuccess(code) ? 'success' : code >= 500 ? 'server error' : 'client error');
}

Output

200 success
204 success
404 client error
500 server error

Explanation: a custom type guard returns a boolean at runtime and narrows the type at compile time.

27. Retry decision with grouped logicReal-world

Decide whether to retry based on typed failure details.

Show solution
type Failure = { status: number; attempt: number; idempotent: boolean };
const MAX = 3;
const shouldRetry = (f: Failure): boolean => f.attempt < MAX && (f.status >= 500 || f.status === 429) && f.idempotent;
const cases: Failure[] = [
  { status: 503, attempt: 1, idempotent: true },
  { status: 404, attempt: 1, idempotent: true },
  { status: 429, attempt: 3, idempotent: true },
  { status: 500, attempt: 1, idempotent: false }
];
for (const c of cases) console.log(c.status, c.attempt, shouldRetry(c));

Output

503 1 true
404 1 false
429 3 false
500 1 false

Explanation: parentheses group the status rule, and typed input makes the rule easy to test case by case.

28. Convert milliseconds with integer operatorsReal-world

Convert durations to m:ss using Math.floor, / and %.

Show solution
const toClock = (ms: number): string => {
  const total = Math.floor(ms / 1000);
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
};
for (const ms of [5000, 65000, 754000]) console.log(ms, '->', toClock(ms));

Output

5000 -> 0:05
65000 -> 1:05
754000 -> 12:34

Explanation: division gives whole minutes and % gives the remaining seconds.

29. Version comparisonReal-world

Compare semantic versions numerically.

Show solution
function compareVersions(a: string, b: string): -1 | 0 | 1 {
  const pa = a.split('.').map(Number);
  const pb = b.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    if (pa[i] > pb[i]) return 1;
    if (pa[i] < pb[i]) return -1;
  }
  return 0;
}
console.log(compareVersions('1.48.2', '1.50.0'), compareVersions('2.0.0', '1.9.9'), compareVersions('1.2.3', '1.2.3'));

Output

-1 1 0

Explanation: the literal return type -1 | 0 | 1 documents exactly which values the function can produce.

30. Exhaustive switch on a unionReal-world

Map browser names to engines, with a compile-time check that all cases are handled.

Show solution
type BrowserName = 'chromium' | 'firefox' | 'webkit';
function engine(b: BrowserName): string {
  switch (b) {
    case 'chromium': return 'Blink';
    case 'firefox': return 'Gecko';
    case 'webkit': return 'WebKit';
    default: { const unhandled: never = b; return unhandled; }
  }
}
const all: BrowserName[] = ['chromium', 'firefox', 'webkit'];
console.log(all.map(engine).join(', '));

Output

Blink, Gecko, WebKit

Explanation: the never assignment fails to compile if a new browser is added to the union but not handled.

Keep Practising

TypeScript Data Types Practice Programs with Solutions (31 Programs)

Practise TypeScript data types with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Data Types lesson first.

TypeScript Beginner Programs

1. The primitive typesBeginner

Declare one variable of each primitive type and print its runtime type.

Show solution
const title: string = 'Login test';
const duration: number = 2.5;
const passed: boolean = true;
const bigId: bigint = 9007199254740993n;
const key: symbol = Symbol('id');
console.log(typeof title, typeof duration, typeof passed, typeof bigId, typeof key);

Output

string number boolean bigint symbol

Explanation: TypeScript’s primitive types match JavaScript’s runtime types.

2. null and undefinedBeginner

Declare variables that can be null or undefined and print them.

Show solution
let selectedOption: string | null = null;
let middleName: string | undefined;
console.log(selectedOption, middleName);
selectedOption = 'Express';
console.log(selectedOption);

Output

null undefined
Express

Explanation: with strictNullChecks, null and undefined must be included in the type explicitly.

3. Arrays in two notationsBeginner

Declare number arrays with number[] and Array&lt;number&gt;.

Show solution
const scores: number[] = [90, 75, 88];
const timings: Array<number> = [120, 340];
console.log(scores.length + timings.length);
console.log(Math.max(...scores));

Output

5
90

Explanation: number[] and Array&lt;number&gt; are the same type. The shorter form is more common.

4. TupleBeginner

Store a username and password pair in a tuple.

Show solution
const credentials: [string, string] = ['qa_user', 'Secret123'];
const [user, pass] = credentials;
console.log(user, pass.length);

Output

qa_user 9

Explanation: a tuple has a fixed length and a type for each position.

5. Tuple with different typesBeginner

Store an HTTP status code and message as [number, string].

Show solution
const response: [number, string] = [404, 'Not Found'];
console.log(`${response[0]} ${response[1]}`);
// @ts-expect-error: Type 'string' is not assignable to type 'number'
const wrong: [number, string] = ['404', 'Not Found'];
console.log(wrong.length);

Output

404 Not Found
2

Explanation: each tuple position is checked separately, so swapped or wrong types are compile errors.

6. Numeric enumBeginner

Create a Priority enum and print a value and its name.

Show solution
enum Priority { Low, Medium, High }
const p: Priority = Priority.High;
console.log(p);
console.log(Priority[p]);

Output

2
High

Explanation: numeric enums start at 0. Reverse mapping turns a number back into its name.

7. String enumBeginner

Create a Browser string enum and use it in a message.

Show solution
enum Browser {
  Chromium = 'chromium',
  Firefox = 'firefox',
  WebKit = 'webkit'
}
const target: Browser = Browser.Firefox;
console.log(`Running on ${target}`);

Output

Running on firefox

Explanation: string enum members have readable values, which is useful in logs and reports.

8. void return typeBeginner

Write a logging function with a void return type.

Show solution
function logStep(step: string): void {
  console.log(`STEP: ${step}`);
}
const result = logStep('Open login page');
console.log(result);

Output

STEP: Open login page
undefined

Explanation: void means the function returns nothing useful. At runtime it returns undefined.

9. Object typeBeginner

Describe a product with an inline object type.

Show solution
const product: { sku: string; price: number; tags: string[] } = {
  sku: 'KB-01',
  price: 1499,
  tags: ['electronics', 'keyboard']
};
console.log(product.sku, product.price, product.tags.join('/'));

Output

KB-01 1499 electronics/keyboard

Explanation: object types list each property name with its type.

10. Date typeBeginner

Create a Date from a fixed ISO string and print parts of it in UTC.

Show solution
const runDate: Date = new Date('2026-11-02T09:30:00Z');
console.log(runDate.toISOString());
console.log(runDate.getUTCFullYear(), runDate.getUTCMonth() + 1, runDate.getUTCDate());

Output

2026-11-02T09:30:00.000Z
2026 11 2

Explanation: built-in classes such as Date are types too. UTC methods avoid time-zone differences.

TypeScript Intermediate Programs

11. unknown vs anyIntermediate

Assign the same value to any and unknown and see which requires a check.

Show solution
const fromApi: unknown = JSON.parse('{"id": 7}');
const anything: any = JSON.parse('{"id": 7}');
console.log(anything.id);
if (typeof fromApi === 'object' && fromApi !== null && 'id' in fromApi) {
  console.log((fromApi as { id: number }).id);
}

Output

7
7

Explanation: unknown forces you to check the shape first, while any lets you access anything without checks.

12. never for exhaustive checksIntermediate

Use never to make sure every status in a union is handled.

Show solution
type Status = 'passed' | 'failed' | 'skipped';
function label(status: Status): string {
  switch (status) {
    case 'passed': return '✔';
    case 'failed': return '✘';
    case 'skipped': return '-';
    default: {
      const unreachable: never = status;
      return unreachable;
    }
  }
}
console.log(['passed', 'failed', 'skipped'].map(s => label(s as Status)).join(' '));

Output

✔ ✘ -

Explanation: if a new status is added to the union, the never assignment fails to compile until it is handled.

13. Union of object typesIntermediate

Model an API result that is either success or error, and print it.

Show solution
type ApiResult = { ok: true; data: string[] } | { ok: false; error: string };
const results: ApiResult[] = [{ ok: true, data: ['a', 'b'] }, { ok: false, error: 'Timeout' }];
for (const r of results) {
  console.log(r.ok ? `Got ${r.data.length} items` : `Failed: ${r.error}`);
}

Output

Got 2 items
Failed: Timeout

Explanation: checking the ok property narrows the union, so data and error are only accessible in the right branch.

14. Intersection typesIntermediate

Combine a User type and a Timestamps type into one.

Show solution
type User = { id: number; name: string };
type Timestamps = { createdAt: string };
type UserRecord = User & Timestamps;
const rec: UserRecord = { id: 1, name: 'Asha', createdAt: '2026-11-01' };
console.log(rec.name, rec.createdAt);

Output

Asha 2026-11-01

Explanation: A &amp; B requires all properties of both types.

15. Type assertion with asIntermediate

Parse JSON and tell TypeScript its shape with as.

Show solution
type Config = { retries: number; baseURL: string };
const config = JSON.parse('{"retries":2,"baseURL":"https://qa.app.test"}') as Config;
console.log(config.retries + 1, config.baseURL);

Output

3 https://qa.app.test

Explanation: as tells the compiler what type to assume. It does not check the data at runtime, so use it only when you trust the source.

16. Optional tuple elementsIntermediate

Use a tuple with an optional third element for a test step.

Show solution
type Step = [action: string, target: string, value?: string];
const steps: Step[] = [['click', 'Login'], ['fill', 'Email', 'qa@test.com']];
for (const [action, target, value] of steps) {
  console.log(value ? `${action} ${target} = ${value}` : `${action} ${target}`);
}

Output

click Login
fill Email = qa@test.com

Explanation: labelled tuple elements document each position, and ? makes the last one optional.

17. Readonly tupleIntermediate

Create a read-only coordinate pair and show the compile error when changing it.

Show solution
const viewport: readonly [number, number] = [1280, 720];
console.log(`${viewport[0]}x${viewport[1]}`);
// @ts-expect-error: Cannot assign to '0' because it is a read-only property
viewport[0] = 1920;

Output

1280x720

Explanation: readonly tuples protect fixed values such as default viewport sizes.

18. Index signaturesIntermediate

Type an object of HTTP headers with unknown keys.

Show solution
const headers: { [name: string]: string } = { 'content-type': 'application/json' };
headers['x-request-id'] = 'abc-123';
console.log(Object.keys(headers).length, headers['content-type']);

Output

2 application/json

Explanation: an index signature allows any string key with values of the declared type.

19. Function typesIntermediate

Declare a variable whose type is a function from string to boolean.

Show solution
type Validator = (value: string) => boolean;
const isEmail: Validator = value => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
const isNotEmpty: Validator = value => value.trim().length > 0;
console.log(isEmail('qa@test.com'), isEmail('qa'), isNotEmpty('  '));

Output

true false false

Explanation: function types describe parameters and return types, so any function assigned must match.

20. bigint arithmeticIntermediate

Add two large order IDs as bigint values.

Show solution
const base: bigint = 9007199254740991n;
const next: bigint = base + 2n;
console.log(next.toString());
try {
  // @ts-expect-error: Operator '+' cannot be applied to types 'bigint' and 'number'
  console.log(base + 1);
} catch (error) {
  console.log('Also fails at runtime:', error instanceof TypeError);
}

Output

9007199254740993
Also fails at runtime: true

Explanation: TypeScript rejects mixing bigint and number at compile time. The same mistake would throw a TypeError in plain JavaScript, so the compiler saves you from a runtime crash.

TypeScript Real-World QA Scenario Programs

21. Typed API responseReal-world

Describe a paginated API response and read its fields.

Show solution
type Product = { id: number; name: string; price: number };
type Page<T> = { items: T[]; page: number; total: number };
const response: Page<Product> = {
  items: [{ id: 1, name: 'Mouse', price: 599 }, { id: 2, name: 'Cable', price: 199 }],
  page: 1,
  total: 12
};
console.log(`Page ${response.page}: ${response.items.length} of ${response.total} items`);
console.log(response.items.map(p => p.name).join(', '));

Output

Page 1: 2 of 12 items
Mouse, Cable

Explanation: a typed response shape gives autocomplete and catches typos such as respose.itmes.

22. Status enum in test resultsReal-world

Use a string enum for test statuses and count them.

Show solution
enum TestStatus { Passed = 'passed', Failed = 'failed', Skipped = 'skipped' }
const runs: TestStatus[] = [TestStatus.Passed, TestStatus.Failed, TestStatus.Passed];
const failed = runs.filter(s => s === TestStatus.Failed).length;
console.log(`${runs.length} runs, ${failed} failed`);

Output

3 runs, 1 failed

Explanation: an enum gives one source of truth for allowed status values.

23. Tuple for table rowsReal-world

Type web-table rows as tuples and total the price column.

Show solution
type Row = [name: string, qty: number, price: number];
const rows: Row[] = [['Pen', 3, 20], ['Book', 1, 350], ['Bag', 2, 899]];
const total = rows.reduce((sum, [, qty, price]) => sum + qty * price, 0);
console.log('Order total:', total);

Output

Order total: 2208

Explanation: tuples fit fixed-column data such as table rows, and destructuring reads the columns by position.

24. Discriminated union for UI eventsReal-world

Handle click and fill events with a discriminated union.

Show solution
type Action =
  | { type: 'click'; selector: string }
  | { type: 'fill'; selector: string; value: string }
  | { type: 'goto'; url: string };
const actions: Action[] = [
  { type: 'goto', url: '/login' },
  { type: 'fill', selector: '#email', value: 'qa@test.com' },
  { type: 'click', selector: 'button[type=submit]' }
];
for (const a of actions) {
  if (a.type === 'goto') console.log('Navigate to', a.url);
  else if (a.type === 'fill') console.log(`Fill ${a.selector} with ${a.value}`);
  else console.log('Click', a.selector);
}

Output

Navigate to /login
Fill #email with qa@test.com
Click button[type=submit]

Explanation: the shared type field tells TypeScript which properties each action has.

25. Validate unknown JSONReal-world

Write a type guard that checks unknown JSON before using it as a User.

Show solution
type User = { id: number; email: string };
function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null &&
    typeof (value as User).id === 'number' && typeof (value as User).email === 'string';
}
for (const text of ['{"id":1,"email":"qa@test.com"}', '{"id":"1"}']) {
  const data: unknown = JSON.parse(text);
  console.log(isUser(data) ? `Valid user ${data.email}` : 'Invalid user data');
}

Output

Valid user qa@test.com
Invalid user data

Explanation: a type guard (value is User) checks at runtime and narrows the type at compile time.

26. Nullable fields from a formReal-world

Handle a form object where optional fields may be null.

Show solution
type Form = { name: string; company: string | null; phone?: string };
const forms: Form[] = [
  { name: 'Asha', company: 'Acme', phone: '98765' },
  { name: 'Ravi', company: null }
];
for (const f of forms) {
  console.log(`${f.name} | ${f.company ?? 'Individual'} | ${f.phone ?? '-'}`);
}

Output

Asha | Acme | 98765
Ravi | Individual | -

Explanation: null (an explicit empty value) and optional fields are both handled with ??.

27. Record of expected textsReal-world

Store expected page titles in a Record keyed by route.

Show solution
type Route = '/' | '/login' | '/cart';
const expectedTitles: Record<Route, string> = { '/': 'Home', '/login': 'Sign in', '/cart': 'Your cart' };
const visited: Route[] = ['/login', '/cart'];
for (const route of visited) console.log(`${route} -> ${expectedTitles[route]}`);

Output

/login -> Sign in
/cart -> Your cart

Explanation: Record&lt;Route, string&gt; requires an entry for every route, so none can be forgotten.

28. Symbol as a unique keyReal-world

Use a symbol to attach hidden metadata to a test object.

Show solution
const meta: unique symbol = Symbol('meta');
const test = { title: 'Login', [meta]: { retries: 2 } };
console.log(Object.keys(test));
console.log(test[meta].retries);

Output

[ 'title' ]
2

Explanation: symbol keys do not appear in Object.keys, so metadata does not interfere with normal properties.

29. Date arithmetic with typesReal-world

Calculate a token expiry 30 minutes after a fixed issue time.

Show solution
const issuedAt: Date = new Date('2026-11-02T10:00:00Z');
const expiresAt: Date = new Date(issuedAt.getTime() + 30 * 60 * 1000);
const remainingMin: number = (expiresAt.getTime() - issuedAt.getTime()) / 60000;
console.log(expiresAt.toISOString(), remainingMin);

Output

2026-11-02T10:30:00.000Z 30

Explanation: getTime() returns a number of milliseconds, which makes date arithmetic type-safe.

30. Map with typed keys and valuesReal-world

Use a Map&lt;string, number&gt; to track response times per endpoint.

Show solution
const timings = new Map<string, number>();
timings.set('/api/login', 220);
timings.set('/api/cart', 480);
timings.set('/api/login', 180);
console.log(timings.size, timings.get('/api/login'));
const slow = [...timings].filter(([, ms]) => ms > 300).map(([url]) => url);
console.log('Slow:', slow.join(', '));

Output

2 180
Slow: /api/cart

Explanation: Map&lt;K, V&gt; types both keys and values. Setting an existing key replaces its value.

31. Set of unique tagsReal-world

Collect unique tags from several tests into a Set&lt;string&gt;.

Show solution
const testTags: string[][] = [['smoke', 'login'], ['regression', 'login'], ['smoke', 'cart']];
const unique = new Set<string>();
for (const tags of testTags) tags.forEach(t => unique.add(t));
console.log(unique.size, [...unique].sort().join(', '));

Output

4 cart, login, regression, smoke

Explanation: a typed Set stores each value once and only accepts the declared type.

Keep Practising

TypeScript Variables Practice Programs with Solutions (31 Programs)

Practise TypeScript variables and types with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning TypeScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Variables lesson first.

TypeScript Beginner Programs

1. Annotate basic variablesBeginner

Declare a string, a number and a boolean with explicit type annotations and print them.

Show solution
const testerName: string = 'Asha';
const experienceYears: number = 4;
const isLead: boolean = false;
console.log(testerName, experienceYears, isLead);

Output

Asha 4 false

Explanation: name: type tells TypeScript what a variable may hold, and the compiler checks every assignment against it.

2. Type inferenceBeginner

Declare variables without annotations and print their runtime types.

Show solution
let browser = 'chromium';
let retries = 2;
let headless = true;
console.log(typeof browser, typeof retries, typeof headless);

Output

string number boolean

Explanation: TypeScript infers string, number and boolean from the initial values, so annotations are often unnecessary.

3. Catch a wrong assignment at compile timeBeginner

Show that assigning a string to a number variable is a compile error, then print the runtime type.

Show solution
let count: number = 5;
// @ts-expect-error: Type 'string' is not assignable to type 'number'
count = 'five';
console.log(typeof count);

Output

string

Explanation: the compiler rejects the assignment. @ts-expect-error documents the expected error. Types are erased at runtime, which is why JavaScript still runs the line.

4. const narrows to a literal typeBeginner

Compare the inferred types of a const and a let holding 'qa'.

Show solution
const envConst = 'qa';
let envLet = 'qa';
envLet = 'staging';
const check: 'qa' = envConst;
console.log(check, envLet);

Output

qa staging

Explanation: a const string is inferred as the literal type 'qa', while a let widens to string because it can change.

5. Union type variableBeginner

Create a variable that may hold a number or a string ID.

Show solution
let userId: number | string = 101;
console.log(userId);
userId = 'USR-101';
console.log(userId);

Output

101
USR-101

Explanation: a union type A | B allows any of the listed types.

6. Literal union for allowed valuesBeginner

Restrict a browser variable to three allowed names.

Show solution
type BrowserName = 'chromium' | 'firefox' | 'webkit';
let browser: BrowserName = 'firefox';
console.log(browser);
// @ts-expect-error: '"edge"' is not assignable to type 'BrowserName'
browser = 'edge';

Output

firefox

Explanation: literal unions turn typos and unsupported values into compile errors.

7. Type aliasBeginner

Create a Url type alias and use it for two variables.

Show solution
type Url = string;
const baseUrl: Url = 'https://qa.shop.test';
const loginUrl: Url = `${baseUrl}/login`;
console.log(loginUrl);

Output

https://qa.shop.test/login

Explanation: a type alias gives a meaningful name to a type, which documents intent.

8. Typed array variableBeginner

Declare an array of test names with a type annotation and add an item.

Show solution
const tests: string[] = ['login', 'search'];
tests.push('checkout');
console.log(tests);
console.log(tests.length);

Output

[ 'login', 'search', 'checkout' ]
3

Explanation: string[] means “array of strings”, so only strings can be pushed.

9. Typed object variableBeginner

Declare a user variable with an inline object type.

Show solution
const user: { name: string; age: number; active: boolean } = { name: 'Ravi', age: 29, active: true };
console.log(`${user.name} (${user.age})`);

Output

Ravi (29)

Explanation: inline object types describe every property and its type.

10. Optional propertyBeginner

Declare an object type where phone is optional and create two users.

Show solution
type Contact = { email: string; phone?: string };
const a: Contact = { email: 'a@test.com' };
const b: Contact = { email: 'b@test.com', phone: '9876543210' };
console.log(a.phone ?? 'no phone', '|', b.phone ?? 'no phone');

Output

no phone | 9876543210

Explanation: ? marks a property as optional, so its type becomes string | undefined.

TypeScript Intermediate Programs

11. readonly propertiesIntermediate

Make id read-only and show the compile error when changing it.

Show solution
type TestCase = { readonly id: string; title: string };
const tc: TestCase = { id: 'TC-1', title: 'Login' };
tc.title = 'Login with SSO';
// @ts-expect-error: Cannot assign to 'id' because it is a read-only property
tc.id = 'TC-2';
console.log(tc.title);

Output

Login with SSO

Explanation: readonly prevents reassignment at compile time.

12. readonly arraysIntermediate

Declare a read-only list of supported browsers.

Show solution
const SUPPORTED: readonly string[] = ['chromium', 'firefox', 'webkit'];
console.log(SUPPORTED.includes('webkit'));
// @ts-expect-error: Property 'push' does not exist on type 'readonly string[]'
SUPPORTED.push('edge');

Output

true

Explanation: read-only arrays have no mutating methods in their type, which protects shared constants.

13. as constIntermediate

Freeze a config object’s types to literals with as const.

Show solution
const config = { browser: 'chromium', workers: 4 } as const;
const browser: 'chromium' = config.browser;
console.log(browser, config.workers);

Output

chromium 4

Explanation: as const makes properties readonly and keeps literal types instead of widening them to string or number.

14. Derive a union from an as const arrayIntermediate

Create a Env type from an array of environment names.

Show solution
const ENVS = ['dev', 'qa', 'staging'] as const;
type Env = (typeof ENVS)[number];
const current: Env = 'qa';
console.log(current, ENVS.length);

Output

qa 3

Explanation: (typeof ENVS)[number] turns the array’s literal values into a union type, so the list and the type stay in sync.

15. unknown requires narrowingIntermediate

Store a value of type unknown and narrow it before using it.

Show solution
let input: unknown = 'qa@example.com';
if (typeof input === 'string') {
  console.log(input.toUpperCase());
}
input = 42;
if (typeof input === 'number') {
  console.log(input.toFixed(1));
}

Output

QA@EXAMPLE.COM
42.0

Explanation: unknown accepts anything, but you must check its type before using it, unlike any.

16. any disables checkingIntermediate

Show that any allows unsafe operations that fail at runtime.

Show solution
let data: any = 'text';
try {
  data.notAMethod();
} catch (error) {
  console.log(error instanceof TypeError ? 'Runtime TypeError' : 'Other error');
}

Output

Runtime TypeError

Explanation: any turns off type checking, so mistakes surface only at runtime. Prefer unknown.

17. Definite assignmentIntermediate

Declare a variable that is assigned inside a branch and use it safely.

Show solution
let status: string;
const passed = 42 > 40;
if (passed) {
  status = 'PASSED';
} else {
  status = 'FAILED';
}
console.log(status);

Output

PASSED

Explanation: TypeScript tracks that status is assigned on every path, so reading it afterwards is allowed.

18. Template literal typesIntermediate

Create a TestId type that must look like TC-&lt;number&gt;.

Show solution
type TestId = `TC-${number}`;
const first: TestId = 'TC-101';
// @ts-expect-error: '"101"' is not assignable to type '`TC-${number}`'
const bad: TestId = '101';
console.log(first, bad);

Output

TC-101 101

Explanation: template literal types describe string patterns, which catches malformed IDs.

19. Destructuring with typesIntermediate

Destructure a typed credentials object into variables.

Show solution
type Credentials = { username: string; password: string; role?: 'admin' | 'viewer' };
const creds: Credentials = { username: 'qa_user', password: 'Secret123' };
const { username, role = 'viewer' } = creds;
console.log(username, role);

Output

qa_user viewer

Explanation: destructured variables keep their property types. The default value narrows role to the literal union.

20. Block-scoped typed variablesIntermediate

Use the same variable name with different types in two blocks.

Show solution
{
  const result: number = 95;
  console.log('score', result);
}
{
  const result: string = 'passed';
  console.log('status', result);
}

Output

score 95
status passed

Explanation: const and let are block-scoped, so each block can declare its own result with its own type.

TypeScript Real-World QA Scenario Programs

21. Environment URL mapReal-world

Use a Record to store base URLs for each environment and look one up.

Show solution
type Env = 'qa' | 'staging' | 'prod';
const BASE_URLS: Record<Env, string> = {
  qa: 'https://qa.shop.test',
  staging: 'https://staging.shop.test',
  prod: 'https://shop.test'
};
const env: Env = 'staging';
console.log(`${BASE_URLS[env]}/login`);

Output

https://staging.shop.test/login

Explanation: Record&lt;Env, string&gt; forces a URL for every environment, so a missing one is a compile error.

22. Typed test configurationReal-world

Declare a typed config object with optional settings and defaults.

Show solution
type RunConfig = { baseURL: string; retries?: number; headless?: boolean };
const config: RunConfig = { baseURL: 'https://qa.app.test' };
const retries = config.retries ?? 0;
const headless = config.headless ?? true;
console.log(config.baseURL, retries, headless);

Output

https://qa.app.test 0 true

Explanation: optional properties plus ?? defaults is a typical shape for test settings.

23. Typed counters for resultsReal-world

Count test results with a typed counter object.

Show solution
type Status = 'passed' | 'failed' | 'skipped';
const counts: Record<Status, number> = { passed: 0, failed: 0, skipped: 0 };
const results: Status[] = ['passed', 'failed', 'passed', 'skipped', 'passed'];
for (const r of results) counts[r]++;
console.log(counts);

Output

{ passed: 3, failed: 1, skipped: 1 }

Explanation: indexing a Record&lt;Status, number&gt; with a Status value is fully type-safe.

24. Typed test userReal-world

Create a typed test user and build an email from it.

Show solution
type Role = 'admin' | 'editor' | 'viewer';
type TestUser = { id: number; name: string; role: Role };
const user: TestUser = { id: 7, name: 'meera', role: 'editor' };
const email = `${user.name}.${user.id}@example.com`;
console.log(email, user.role);

Output

meera.7@example.com editor

Explanation: a named type documents the test-data shape and catches invalid roles.

25. Read environment variables safelyReal-world

Read optional environment values with fallbacks and convert types.

Show solution
const env: Record<string, string | undefined> = { BASE_URL: 'https://qa.app.test', WORKERS: '4' };
const baseUrl: string = env.BASE_URL ?? 'http://localhost:3000';
const workers: number = Number(env.WORKERS ?? '2');
const debug: boolean = env.DEBUG === 'true';
console.log(baseUrl, workers, debug);

Output

https://qa.app.test 4 false

Explanation: environment values are string | undefined, so the types force you to handle missing values and convert them.

26. Timeouts as named constantsReal-world

Store timeouts in a typed constant object and calculate a total wait.

Show solution
const TIMEOUTS = { navigation: 30000, action: 10000, assertion: 5000 } as const;
type TimeoutName = keyof typeof TIMEOUTS;
const steps: TimeoutName[] = ['navigation', 'action', 'action', 'assertion'];
const worstCase = steps.reduce((sum, s) => sum + TIMEOUTS[s], 0);
console.log(`Worst case: ${worstCase / 1000}s`);

Output

Worst case: 55s

Explanation: keyof typeof builds a union of the object’s keys, so only real timeout names can be used.

27. Typed locator strategyReal-world

Model a locator as either a role or a test ID using a union of object types.

Show solution
type Locator = { by: 'role'; role: string; name: string } | { by: 'testId'; id: string };
const locators: Locator[] = [
  { by: 'role', role: 'button', name: 'Login' },
  { by: 'testId', id: 'cart-badge' }
];
for (const l of locators) {
  console.log(l.by === 'role' ? `getByRole('${l.role}', { name: '${l.name}' })` : `getByTestId('${l.id}')`);
}

Output

getByRole('button', { name: 'Login' })
getByTestId('cart-badge')

Explanation: checking by narrows the union, so TypeScript knows which properties exist in each branch.

28. Track state with typed let variablesReal-world

Track login attempts with typed state variables.

Show solution
const MAX_ATTEMPTS: number = 3;
let attempts: number = 0;
let locked: boolean = false;
const outcomes: boolean[] = [false, false, false];
for (const ok of outcomes) {
  if (ok) break;
  attempts++;
  locked = attempts >= MAX_ATTEMPTS;
}
console.log(`attempts=${attempts}, locked=${locked}`);

Output

attempts=3, locked=true

Explanation: explicit types make it clear which values change and what they may contain.

29. Build a typed report lineReal-world

Create typed variables for a test result and format a report line.

Show solution
type Result = { title: string; durationMs: number; status: 'passed' | 'failed' };
const result: Result = { title: 'Checkout with coupon', durationMs: 4210, status: 'passed' };
const line: string = `[${result.status.toUpperCase()}] ${result.title} - ${(result.durationMs / 1000).toFixed(1)}s`;
console.log(line);

Output

[PASSED] Checkout with coupon - 4.2s

Explanation: typed inputs guarantee that toUpperCase and toFixed are called on the right types.

30. Nullable variable for a found elementReal-world

Model a search result that may be null and handle both cases.

Show solution
const products = ['Mouse', 'Keyboard', 'Monitor'];
function findProduct(name: string): string | null {
  return products.find(p => p === name) ?? null;
}
for (const name of ['Keyboard', 'Webcam']) {
  const found: string | null = findProduct(name);
  console.log(found === null ? `${name} not found` : `Found ${found}`);
}

Output

Found Keyboard
Webcam not found

Explanation: with strictNullChecks, a string | null value must be checked before it is used as a string.

31. Variables typed from another variableReal-world

Use typeof to type a new object like an existing default config.

Show solution
const defaultUser = { name: 'QA User', role: 'viewer', active: true };
const admin: typeof defaultUser = { ...defaultUser, name: 'Admin', role: 'admin' };
console.log(admin);

Output

{ name: 'Admin', role: 'admin', active: true }

Explanation: typeof value in a type position copies the inferred type of an existing value.

Keep Practising

JavaScript Async/Await Practice Programs with Solutions (31 Programs)

Practise JavaScript promises and async/await with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Async/Await lesson first.

JavaScript Beginner Programs

1. Synchronous vs asynchronous orderBeginner

Predict the order of logs when one of them is inside setTimeout.

Show solution
console.log('1. start');
setTimeout(() => console.log('3. timeout callback'), 0);
console.log('2. end');
await new Promise(resolve => setTimeout(resolve, 10));

Output

1. start
2. end
3. timeout callback

Explanation: setTimeout callbacks run later, after the current code finishes, even with a 0 ms delay.

2. Create and resolve a promiseBeginner

Create a promise that resolves with 'done' and print the result with then.

Show solution
const task = new Promise(resolve => resolve('done'));
task.then(value => console.log('Result:', value));
await task;

Output

Result: done

Explanation: a promise represents a future value. then runs when it resolves.

3. Reject a promise and catch itBeginner

Create a promise that rejects and handle it with catch.

Show solution
const failing = new Promise((resolve, reject) => reject(new Error('Network error')));
await failing.catch(error => console.log('Caught:', error.message));

Output

Caught: Network error

Explanation: reject signals failure, and .catch handles it.

4. A sleep helperBeginner

Write sleep(ms) that returns a promise, and await it between two logs.

Show solution
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
console.log('Waiting...');
await sleep(50);
console.log('Done after 50 ms');

Output

Waiting...
Done after 50 ms

Explanation: wrapping setTimeout in a promise makes delays awaitable. In Playwright tests, prefer auto-waiting over fixed sleeps.

5. Async function returns a promiseBeginner

Show that an async function always returns a promise.

Show solution
async function getTitle() {
  return 'Playwright';
}
const result = getTitle();
console.log(result instanceof Promise);
console.log(await result);

Output

true
Playwright

Explanation: async wraps the return value in a resolved promise. Use await to read the value.

6. await inside an async functionBeginner

Await a simulated API call inside an async function.

Show solution
const fetchUser = () => new Promise(resolve => setTimeout(() => resolve({ name: 'Asha' }), 20));
async function showUser() {
  const user = await fetchUser();
  console.log('User:', user.name);
}
await showUser();

Output

User: Asha

Explanation: await pauses the async function until the promise settles, without blocking other work.

7. try/catch with awaitBeginner

Catch a rejected promise using try/catch and await.

Show solution
const login = () => Promise.reject(new Error('Invalid credentials'));
try {
  await login();
} catch (error) {
  console.log('Login failed:', error.message);
}

Output

Login failed: Invalid credentials

Explanation: with await, rejected promises throw, so normal try/catch handles them.

8. Chain then callsBeginner

Chain three then calls that transform a value step by step.

Show solution
const total = await Promise.resolve(10)
  .then(n => n * 2)
  .then(n => n + 5)
  .then(n => `Total: ${n}`);
console.log(total);

Output

Total: 25

Explanation: each then receives the previous result and returns a new value to the next step.

9. finally on a promiseBeginner

Use finally to log cleanup after success and after failure.

Show solution
await Promise.resolve('ok').then(v => console.log('Success:', v)).finally(() => console.log('cleanup 1'));
await Promise.reject(new Error('fail')).catch(e => console.log('Error:', e.message)).finally(() => console.log('cleanup 2'));

Output

Success: ok
cleanup 1
Error: fail
cleanup 2

Explanation: finally runs whether the promise resolved or rejected, just like in try/catch/finally.

10. Promise.resolve and Promise.rejectBeginner

Create already-settled promises and read their values.

Show solution
const ok = await Promise.resolve(200);
console.log('Status:', ok);
const err = await Promise.reject(new Error('timeout')).catch(e => e.message);
console.log('Error:', err);

Output

Status: 200
Error: timeout

Explanation: Promise.resolve and Promise.reject create settled promises, which is useful in tests and mocks.

JavaScript Intermediate Programs

11. Sequential vs parallel timingIntermediate

Run two 50 ms tasks one after another, then in parallel, and compare the elapsed time.

Show solution
const task = (name, ms) => new Promise(r => setTimeout(() => r(name), ms));
let start = Date.now();
await task('A', 50);
await task('B', 50);
const sequential = Date.now() - start;
start = Date.now();
await Promise.all([task('A', 50), task('B', 50)]);
const parallel = Date.now() - start;
console.log('Parallel faster:', parallel < sequential);

Output

Parallel faster: true

Explanation: awaiting one by one adds up the delays. Promise.all runs independent tasks at the same time.

12. Promise.all results orderIntermediate

Run three tasks with different delays in parallel and print the results.

Show solution
const task = (name, ms) => new Promise(r => setTimeout(() => r(name), ms));
const results = await Promise.all([task('slow', 60), task('fast', 10), task('medium', 30)]);
console.log(results);

Output

[ 'slow', 'fast', 'medium' ]

Explanation: Promise.all returns results in the order of the input array, not in completion order.

13. Promise.all fails fastIntermediate

Show that Promise.all rejects as soon as any promise rejects.

Show solution
const ok = ms => new Promise(r => setTimeout(() => r('ok'), ms));
const fail = ms => new Promise((_, reject) => setTimeout(() => reject(new Error('API 500')), ms));
try {
  await Promise.all([ok(30), fail(10), ok(20)]);
} catch (error) {
  console.log('Promise.all rejected:', error.message);
}

Output

Promise.all rejected: API 500

Explanation: one rejection rejects the whole Promise.all. Use allSettled when you need every result.

14. Promise.allSettledIntermediate

Get the status of every promise, even when some fail.

Show solution
const results = await Promise.allSettled([
  Promise.resolve('page loaded'),
  Promise.reject(new Error('image failed')),
  Promise.resolve('fonts loaded')
]);
for (const r of results) console.log(r.status, r.status === 'fulfilled' ? r.value : r.reason.message);

Output

fulfilled page loaded
rejected image failed
fulfilled fonts loaded

Explanation: allSettled never rejects. It reports fulfilled or rejected for each promise.

15. Promise.race for timeoutsIntermediate

Use Promise.race to fail a slow request after 30 ms.

Show solution
const request = new Promise(r => setTimeout(() => r('response'), 100));
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Request timed out')), 30));
try {
  console.log(await Promise.race([request, timeout]));
} catch (error) {
  console.log(error.message);
}

Output

Request timed out

Explanation: Promise.race settles with whichever promise settles first, which makes it a simple timeout tool.

16. Promise.anyIntermediate

Use Promise.any to get the first successful mirror, ignoring failures.

Show solution
const mirror = (name, ms, ok) => new Promise((res, rej) => setTimeout(() => (ok ? res(name) : rej(new Error(name))), ms));
const fastest = await Promise.any([mirror('mirror-a', 10, false), mirror('mirror-b', 30, true), mirror('mirror-c', 50, true)]);
console.log('First success:', fastest);

Output

First success: mirror-b

Explanation: Promise.any resolves with the first fulfilled promise and only rejects if all of them fail.

17. Convert a callback to a promiseIntermediate

Wrap a callback-style function in a promise.

Show solution
function readConfig(callback) {
  setTimeout(() => callback(null, { retries: 2 }), 10);
}
const readConfigAsync = () =>
  new Promise((resolve, reject) => readConfig((err, data) => (err ? reject(err) : resolve(data))));
const config = await readConfigAsync();
console.log('Retries:', config.retries);

Output

Retries: 2

Explanation: wrapping callbacks in promises lets old APIs work with async/await.

18. Microtasks before timersIntermediate

Compare the order of Promise.then and setTimeout callbacks.

Show solution
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('sync');
await new Promise(r => setTimeout(r, 10));

Output

sync
promise
timeout

Explanation: promise callbacks are microtasks and run before timer callbacks, even with a 0 ms delay.

19. forEach does not waitIntermediate

Show why forEach with async callbacks does not wait, and fix it with for...of.

Show solution
const delay = ms => new Promise(r => setTimeout(r, ms));
const steps = ['one', 'two'];
steps.forEach(async step => { await delay(20); console.log('forEach finished', step); });
console.log('after forEach');
await delay(50);
for (const step of steps) { await delay(5); console.log('for...of finished', step); }
console.log('after for...of');

Output

after forEach
forEach finished one
forEach finished two
for...of finished one
for...of finished two
after for...of

Explanation: forEach ignores returned promises, so the code after it runs first. for...of with await waits for each step.

20. Async iteration with map and Promise.allIntermediate

Fetch details for several IDs in parallel using map and Promise.all.

Show solution
const getProduct = id => new Promise(r => setTimeout(() => r({ id, price: id * 100 }), 10));
const ids = [1, 2, 3];
const products = await Promise.all(ids.map(getProduct));
console.log(products.map(p => `#${p.id}=${p.price}`).join(', '));

Output

#1=100, #2=200, #3=300

Explanation: map creates one promise per item, and Promise.all waits for all of them.

JavaScript Real-World QA Scenario Programs

21. Retry an async actionReal-world

Retry a flaky async call up to 3 times with a short delay between attempts.

Show solution
const sleep = ms => new Promise(r => setTimeout(r, ms));
let calls = 0;
async function flakyApi() {
  calls++;
  if (calls < 3) throw new Error(`503 on call ${calls}`);
  return 'data';
}
async function retry(fn, attempts, delayMs) {
  for (let i = 1; i <= attempts; i++) {
    try { return await fn(); }
    catch (error) { console.log(`Attempt ${i} failed: ${error.message}`); if (i < attempts) await sleep(delayMs); }
  }
  throw new Error('All retries failed');
}
console.log('Result:', await retry(flakyApi, 3, 10));

Output

Attempt 1 failed: 503 on call 1
Attempt 2 failed: 503 on call 2
Result: data

Explanation: return await inside try makes rejected promises reach the catch, so the loop can retry.

22. Poll until a job completesReal-world

Poll a job status every 10 ms until it is 'done', with a maximum number of polls.

Show solution
const sleep = ms => new Promise(r => setTimeout(r, ms));
const statuses = ['queued', 'running', 'running', 'done'];
let call = 0;
const getStatus = async () => statuses[Math.min(call++, statuses.length - 1)];
async function waitForDone(maxPolls) {
  for (let i = 1; i <= maxPolls; i++) {
    const status = await getStatus();
    console.log(`Poll ${i}: ${status}`);
    if (status === 'done') return true;
    await sleep(10);
  }
  return false;
}
console.log('Completed:', await waitForDone(10));

Output

Poll 1: queued
Poll 2: running
Poll 3: running
Poll 4: done
Completed: true

Explanation: polling with a limit is how tests wait for background jobs. Playwright’s expect.poll does this for you.

23. Timeout wrapperReal-world

Write withTimeout(promise, ms) that rejects when a promise takes too long.

Show solution
function withTimeout(promise, ms) {
  let timer;
  const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms); });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const slow = new Promise(r => setTimeout(() => r('slow result'), 80));
const fast = new Promise(r => setTimeout(() => r('fast result'), 10));
console.log(await withTimeout(fast, 50));
try { await withTimeout(slow, 30); } catch (e) { console.log(e.message); }

Output

fast result
Timed out after 30 ms

Explanation: clearing the timer in finally avoids leaving stray timers running after the race settles.

24. Run test steps sequentiallyReal-world

Run login, search and checkout steps one after another and log each step.

Show solution
const sleep = ms => new Promise(r => setTimeout(r, ms));
const steps = [
  { name: 'login', run: async () => { await sleep(10); return 'logged in'; } },
  { name: 'search', run: async () => { await sleep(5); return '3 results'; } },
  { name: 'checkout', run: async () => { await sleep(8); return 'order placed'; } }
];
for (const step of steps) console.log(`${step.name}: ${await step.run()}`);

Output

login: logged in
search: 3 results
checkout: order placed

Explanation: dependent steps must run in order, so await each one before starting the next.

25. Parallel API setupReal-world

Create test data through three independent API calls in parallel.

Show solution
const api = (name, ms) => new Promise(r => setTimeout(() => r(`${name} created`), ms));
const [user, product, coupon] = await Promise.all([api('user', 30), api('product', 20), api('coupon', 10)]);
console.log(user);
console.log(product);
console.log(coupon);

Output

user created
product created
coupon created

Explanation: independent setup steps can run together, which makes test setup faster.

26. Collect results from flaky servicesReal-world

Check three health endpoints and report which are down, without stopping at the first failure.

Show solution
const check = (name, up, ms) => new Promise((res, rej) => setTimeout(() => (up ? res(name) : rej(new Error(name))), ms));
const results = await Promise.allSettled([check('auth', true, 10), check('search', false, 20), check('payments', true, 15)]);
const down = results.filter(r => r.status === 'rejected').map(r => r.reason.message);
console.log('Up:', results.length - down.length, '| Down:', down.join(', ') || 'none');

Output

Up: 2 | Down: search

Explanation: allSettled collects every outcome, so one failed service does not hide the others.

27. Limit concurrencyReal-world

Run 5 tasks with at most 2 running at the same time.

Show solution
const sleep = ms => new Promise(r => setTimeout(r, ms));
let running = 0, maxRunning = 0;
async function job(id) {
  running++; maxRunning = Math.max(maxRunning, running);
  await sleep(10);
  running--;
  return id;
}
async function runWithLimit(ids, limit) {
  const results = [];
  for (let i = 0; i < ids.length; i += limit) {
    results.push(...(await Promise.all(ids.slice(i, i + limit).map(job))));
  }
  return results;
}
console.log(await runWithLimit([1, 2, 3, 4, 5], 2));
console.log('Max running at once:', maxRunning);

Output

[ 1, 2, 3, 4, 5 ]
Max running at once: 2

Explanation: processing in batches protects APIs from too many simultaneous requests, similar to limiting workers.

28. Measure an async step’s durationReal-world

Measure how long an async step takes and flag it as slow when it exceeds 40 ms.

Show solution
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function timed(name, fn, limitMs) {
  const start = Date.now();
  await fn();
  const ms = Date.now() - start;
  console.log(`${name}: ${ms >= limitMs ? 'SLOW' : 'ok'}`);
}
await timed('load dashboard', () => sleep(10), 40);
await timed('export report', () => sleep(60), 40);

Output

load dashboard: ok
export report: SLOW

Explanation: timing async steps helps spot performance regressions in end-to-end flows.

29. Async error in one of several stepsReal-world

Stop the flow when a step fails and report which step failed.

Show solution
const steps = [
  ['open page', async () => 'ok'],
  ['submit form', async () => { throw new Error('button disabled'); }],
  ['verify message', async () => 'ok']
];
try {
  for (const [name, run] of steps) {
    await run();
    console.log('✔', name);
  }
} catch (error) {
  console.log('✘ Flow stopped:', error.message);
}

Output

✔ open page
✘ Flow stopped: button disabled

Explanation: with await in a loop, the first rejection jumps to catch and the remaining steps are skipped.

30. Wait for a conditionReal-world

Write waitFor(condition, timeout, interval) that resolves when a condition becomes true.

Show solution
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function waitFor(condition, timeout = 200, interval = 10) {
  const end = Date.now() + timeout;
  while (Date.now() < end) {
    if (condition()) return true;
    await sleep(interval);
  }
  throw new Error('Condition not met in time');
}
let ready = false;
setTimeout(() => { ready = true; }, 40);
console.log('Ready:', await waitFor(() => ready));
try { await waitFor(() => false, 30); } catch (e) { console.log(e.message); }

Output

Ready: true
Condition not met in time

Explanation: this is the idea behind Playwright’s auto-waiting: check repeatedly until it passes or times out.

31. Async generator for paginated dataReal-world

Use an async generator to read pages until there are no more.

Show solution
const pages = [[1, 2], [3, 4], [5]];
async function* fetchAll() {
  for (let page = 0; page < pages.length; page++) {
    await new Promise(r => setTimeout(r, 5));
    yield* pages[page];
  }
}
const items = [];
for await (const item of fetchAll()) items.push(item);
console.log(items);

Output

[ 1, 2, 3, 4, 5 ]

Explanation: for await...of consumes async iterators, which suits paginated APIs and streams.

Keep Practising

JavaScript Exception Handling Practice Programs with Solutions (30 Programs)

Practise JavaScript exception handling with 30 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Exception Handling lesson first.

JavaScript Beginner Programs

1. Basic try/catchBeginner

Parse invalid JSON inside try/catch and print the error name.

Show solution
try {
  JSON.parse('{ invalid json }');
} catch (error) {
  console.log('Caught:', error.name);
}
console.log('Program continues');

Output

Caught: SyntaxError
Program continues

Explanation: catch receives the thrown error, so the program can continue instead of crashing.

2. finally always runsBeginner

Show that finally runs both when an error happens and when it does not.

Show solution
for (const input of ['{"ok":true}', 'oops']) {
  try {
    JSON.parse(input);
    console.log('Parsed', input);
  } catch (error) {
    console.log('Failed to parse', input);
  } finally {
    console.log('Cleanup done');
  }
}

Output

Parsed {"ok":true}
Cleanup done
Failed to parse oops
Cleanup done

Explanation: finally is the place for cleanup, such as closing files or browsers, because it always runs.

3. Throw a custom errorBeginner

Write divide(a, b) that throws an error when b is 0.

Show solution
function divide(a, b) {
  if (b === 0) throw new Error('Cannot divide by zero');
  return a / b;
}
try {
  console.log(divide(10, 2));
  console.log(divide(5, 0));
} catch (error) {
  console.log('Error:', error.message);
}

Output

5
Error: Cannot divide by zero

Explanation: throw stops the function and passes the error to the nearest catch.

4. Error propertiesBeginner

Print the name and message of a caught error.

Show solution
try {
  throw new Error('Login button not found');
} catch (error) {
  console.log(error.name);
  console.log(error.message);
  console.log(error instanceof Error);
}

Output

Error
Login button not found
true

Explanation: every Error has a name, a message and a stack trace.

5. ReferenceErrorBeginner

Use an undefined variable inside try and print the error type.

Show solution
try {
  console.log(undefinedVariable);
} catch (error) {
  console.log(error.name);
}

Output

ReferenceError

Explanation: using a name that was never declared throws a ReferenceError.

6. TypeErrorBeginner

Call a method on undefined and print the error type.

Show solution
const response = {};
try {
  response.data.items.length;
} catch (error) {
  console.log(error.name);
}

Output

TypeError

Explanation: reading a property of undefined throws a TypeError, one of the most common test-script errors.

7. RangeErrorBeginner

Create an array with a negative length and catch the error.

Show solution
try {
  new Array(-1);
} catch (error) {
  console.log(error.name, '-', error.message);
}

Output

RangeError - Invalid array length

Explanation: a RangeError means a value is outside the allowed range.

8. Validate input and throwBeginner

Throw a TypeError when age is not a number.

Show solution
function setAge(age) {
  if (typeof age !== 'number') throw new TypeError('age must be a number');
  return `Age set to ${age}`;
}
for (const value of [30, 'thirty']) {
  try {
    console.log(setAge(value));
  } catch (error) {
    console.log(`${error.name}: ${error.message}`);
  }
}

Output

Age set to 30
TypeError: age must be a number

Explanation: throwing the most specific built-in error type tells callers what went wrong.

9. catch without a bindingBeginner

Use catch without naming the error variable when you do not need it.

Show solution
function isValidJson(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}
console.log(isValidJson('[1, 2]'));
console.log(isValidJson('[1, 2'));

Output

true
false

Explanation: modern JavaScript allows catch { } without (error) when the error itself is not used.

10. Return a default on failureBeginner

Read a number from text and fall back to 0 when it is invalid.

Show solution
function toNumberOrZero(text) {
  try {
    const n = Number(text);
    if (Number.isNaN(n)) throw new Error('not a number');
    return n;
  } catch {
    return 0;
  }
}
console.log(toNumberOrZero('42'), toNumberOrZero('abc'));

Output

42 0

Explanation: catching and returning a default keeps the program running with a safe value.

JavaScript Intermediate Programs

11. Custom error classIntermediate

Create ValidationError with a field property and catch it.

Show solution
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}
try {
  throw new ValidationError('email', 'Email is required');
} catch (error) {
  console.log(error.name, error.field, error.message);
}

Output

ValidationError email Email is required

Explanation: custom error classes carry extra details and can be identified by type.

12. Handle different error typesIntermediate

Handle ValidationError and other errors differently with instanceof.

Show solution
class ValidationError extends Error {}
function run(action) {
  try {
    action();
  } catch (error) {
    if (error instanceof ValidationError) console.log('Fix your input:', error.message);
    else if (error instanceof TypeError) console.log('Bug in code:', error.message);
    else console.log('Unknown error:', error.message);
  }
}
run(() => { throw new ValidationError('password too short'); });
run(() => { null.click(); });
run(() => { throw new Error('network down'); });

Output

Fix your input: password too short
Bug in code: Cannot read properties of null (reading 'click')
Unknown error: network down

Explanation: instanceof lets one catch block react differently to each kind of error.

13. Rethrow unexpected errorsIntermediate

Handle only SyntaxError while parsing and rethrow anything else.

Show solution
function parseConfig(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) return {};
    throw error;
  }
}
console.log(parseConfig('{"retries":2}'));
console.log(parseConfig('not json'));

Output

{ retries: 2 }
{}

Explanation: catch only what you can handle. Rethrowing other errors keeps real bugs visible.

14. Error cause chainingIntermediate

Wrap a low-level error in a higher-level one using cause.

Show solution
function loadUser() {
  try {
    JSON.parse('{bad');
  } catch (error) {
    throw new Error('Could not load user', { cause: error });
  }
}
try {
  loadUser();
} catch (error) {
  console.log(error.message);
  console.log('Caused by:', error.cause.name);
}

Output

Could not load user
Caused by: SyntaxError

Explanation: cause preserves the original error, so you get a clear message without losing the root cause.

15. Nested try/catchIntermediate

Use an inner try/catch for an optional step and an outer one for critical steps.

Show solution
try {
  console.log('Step 1: open page');
  try {
    throw new Error('cookie banner not found');
  } catch (inner) {
    console.log('Optional step skipped:', inner.message);
  }
  console.log('Step 2: login');
  throw new Error('login failed');
} catch (outer) {
  console.log('Test failed:', outer.message);
}

Output

Step 1: open page
Optional step skipped: cookie banner not found
Step 2: login
Test failed: login failed

Explanation: the inner catch handles a recoverable problem, while the outer one still catches fatal errors.

16. finally with returnIntermediate

Show that finally runs even when try returns a value.

Show solution
function getStatus() {
  try {
    return 'from try';
  } finally {
    console.log('finally runs before the value is returned');
  }
}
console.log(getStatus());

Output

finally runs before the value is returned
from try

Explanation: finally runs before the function actually returns, which guarantees cleanup.

17. Collect errors instead of stoppingIntermediate

Validate several fields and collect all errors.

Show solution
const checks = [
  () => { if (!'qa@test.com'.includes('@')) throw new Error('bad email'); },
  () => { if ('123'.length < 8) throw new Error('password too short'); },
  () => { if (Number('abc') !== Number('abc')) throw new Error('age is not a number'); }
];
const errors = [];
for (const check of checks) {
  try { check(); } catch (error) { errors.push(error.message); }
}
console.log(errors.join(' | '));

Output

password too short | age is not a number

Explanation: catching inside the loop lets every check run, like Playwright’s soft assertions.

18. Error-first result objectsIntermediate

Return { ok, value, error } instead of throwing.

Show solution
function safeParse(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (error) {
    return { ok: false, error: error.message.split(' in JSON')[0] };
  }
}
console.log(safeParse('[1]').ok);
console.log(safeParse('{oops').ok);

Output

true
false

Explanation: result objects make failures part of the normal return value, which is handy in data pipelines.

19. Assertion functionIntermediate

Write assert(condition, message) that throws when the condition is false.

Show solution
function assert(condition, message) {
  if (!condition) throw new Error(`Assertion failed: ${message}`);
}
try {
  assert(2 + 2 === 4, 'maths works');
  console.log('First assertion passed');
  assert('Login'.length === 4, 'title length');
} catch (error) {
  console.log(error.message);
}

Output

First assertion passed
Assertion failed: title length

Explanation: tests are built on assertions that throw when expectations are not met.

JavaScript Real-World QA Scenario Programs

20. Retry on failureReal-world

Retry a flaky action up to 3 times before giving up.

Show solution
let calls = 0;
function clickButton() {
  calls++;
  if (calls < 3) throw new Error(`element detached (call ${calls})`);
  return 'clicked';
}
let result;
for (let attempt = 1; attempt <= 3; attempt++) {
  try {
    result = clickButton();
    break;
  } catch (error) {
    console.log(`Attempt ${attempt} failed: ${error.message}`);
  }
}
console.log('Result:', result);

Output

Attempt 1 failed: element detached (call 1)
Attempt 2 failed: element detached (call 2)
Result: clicked

Explanation: catch, log and retry. break leaves the loop as soon as an attempt succeeds.

21. Safe JSON test-data loaderReal-world

Load JSON test data and report a clear message for invalid content.

Show solution
function loadTestData(name, text) {
  try {
    const data = JSON.parse(text);
    if (!Array.isArray(data)) throw new Error('expected an array');
    return data;
  } catch (error) {
    console.log(`${name}: ${error instanceof SyntaxError ? 'invalid JSON' : error.message}`);
    return [];
  }
}
console.log(loadTestData('users.json', '[{"id":1}]').length);
console.log(loadTestData('broken.json', '[{"id":1}').length);
console.log(loadTestData('object.json', '{"id":1}').length);

Output

1
broken.json: invalid JSON
0
object.json: expected an array
0

Explanation: clear error messages save time when test data files are malformed.

22. Validate a signup formReal-world

Throw a ValidationError for the first invalid field and show it to the user.

Show solution
class ValidationError extends Error {
  constructor(field, message) { super(message); this.name = 'ValidationError'; this.field = field; }
}
function validate({ email, password }) {
  if (!email?.includes('@')) throw new ValidationError('email', 'Enter a valid email');
  if (!password || password.length < 8) throw new ValidationError('password', 'Use at least 8 characters');
  return 'Form is valid';
}
for (const form of [{ email: 'qa', password: '12345678' }, { email: 'qa@test.com', password: '123' }, { email: 'qa@test.com', password: 'Secret123' }]) {
  try { console.log(validate(form)); }
  catch (e) { console.log(`[${e.field}] ${e.message}`); }
}

Output

[email] Enter a valid email
[password] Use at least 8 characters
Form is valid

Explanation: a field name on the error lets the UI show the message next to the right input.

23. Map HTTP status codes to errorsReal-world

Throw a specific error for each failing status code.

Show solution
class HttpError extends Error {
  constructor(status) { super(`HTTP ${status}`); this.status = status; }
}
function checkResponse(status) {
  if (status >= 200 && status < 300) return 'OK';
  throw new HttpError(status);
}
for (const status of [200, 404, 503]) {
  try {
    console.log(status, checkResponse(status));
  } catch (error) {
    const hint = error.status >= 500 ? 'server problem, retry later' : 'check the request';
    console.log(status, error.message, '-', hint);
  }
}

Output

200 OK
404 HTTP 404 - check the request
503 HTTP 503 - server problem, retry later

Explanation: a status code on the error lets callers decide whether to retry or fail fast.

24. Always release resourcesReal-world

Simulate opening and closing a browser, closing it even when the test fails.

Show solution
function runTest(shouldFail) {
  console.log('Browser opened');
  try {
    if (shouldFail) throw new Error('assertion failed');
    console.log('Test passed');
  } catch (error) {
    console.log('Test failed:', error.message);
  } finally {
    console.log('Browser closed');
  }
}
runTest(false);
runTest(true);

Output

Browser opened
Test passed
Browser closed
Browser opened
Test failed: assertion failed
Browser closed

Explanation: finally guarantees cleanup, which is what Playwright fixtures do after use().

25. Soft assertionsReal-world

Check several page values and report all failures at the end.

Show solution
const page = { title: 'Shop', cartCount: 2, user: 'guest' };
const expected = { title: 'Shop', cartCount: 3, user: 'asha' };
const failures = [];
for (const key of Object.keys(expected)) {
  try {
    if (page[key] !== expected[key]) throw new Error(`${key}: expected ${expected[key]}, got ${page[key]}`);
  } catch (error) {
    failures.push(error.message);
  }
}
console.log(failures.length ? `${failures.length} failures\n- ${failures.join('\n- ')}` : 'All checks passed');

Output

2 failures
- cartCount: expected 3, got 2
- user: expected asha, got guest

Explanation: collecting failures shows every problem in one run, like expect.soft in Playwright.

26. Timeout errorReal-world

Throw a TimeoutError when a simulated wait exceeds its limit.

Show solution
class TimeoutError extends Error {
  constructor(ms) { super(`Timed out after ${ms} ms`); this.name = 'TimeoutError'; }
}
function waitForElement(appearsAfterMs, timeoutMs) {
  if (appearsAfterMs > timeoutMs) throw new TimeoutError(timeoutMs);
  return `Element visible after ${appearsAfterMs} ms`;
}
for (const appears of [800, 7000]) {
  try { console.log(waitForElement(appears, 5000)); }
  catch (e) { console.log(`${e.name}: ${e.message}`); }
}

Output

Element visible after 800 ms
TimeoutError: Timed out after 5000 ms

Explanation: a named error type makes timeouts easy to recognise in reports and retry logic.

27. Error message for a missing elementReal-world

Build a helpful error message that lists the available options when a menu item is missing.

Show solution
function clickMenuItem(menu, name) {
  if (!menu.includes(name)) {
    throw new Error(`Menu item '${name}' not found. Available: ${menu.join(', ')}`);
  }
  return `Clicked ${name}`;
}
const menu = ['Home', 'Shop', 'Contact'];
try {
  console.log(clickMenuItem(menu, 'Shop'));
  console.log(clickMenuItem(menu, 'Blog'));
} catch (error) {
  console.log(error.message);
}

Output

Clicked Shop
Menu item 'Blog' not found. Available: Home, Shop, Contact

Explanation: including context in error messages turns a vague failure into an obvious fix.

28. Fail fast on missing configReal-world

Throw at start-up when required environment variables are missing.

Show solution
function requireEnv(env, names) {
  const missing = names.filter(name => !env[name]);
  if (missing.length) throw new Error(`Missing environment variables: ${missing.join(', ')}`);
  return 'Config OK';
}
try {
  console.log(requireEnv({ BASE_URL: 'https://qa.app.test', USERNAME: 'qa' }, ['BASE_URL', 'USERNAME']));
  console.log(requireEnv({ BASE_URL: 'https://qa.app.test' }, ['BASE_URL', 'USERNAME', 'PASSWORD']));
} catch (error) {
  console.log(error.message);
}

Output

Config OK
Missing environment variables: USERNAME, PASSWORD

Explanation: failing immediately with a clear message beats confusing failures halfway through a test run.

29. Log errors with contextReal-world

Wrap a step so errors include the step name.

Show solution
function step(name, fn) {
  try {
    fn();
    console.log(`✔ ${name}`);
  } catch (error) {
    throw new Error(`Step "${name}" failed: ${error.message}`);
  }
}
try {
  step('open home page', () => {});
  step('add item to cart', () => { throw new Error('button disabled'); });
  step('checkout', () => {});
} catch (error) {
  console.log(error.message);
}

Output

✔ open home page
Step "add item to cart" failed: button disabled

Explanation: adding the step name to the error is what Playwright’s test.step does in reports.

30. Count error types in a logReal-world

Count how many errors of each type appear in a list of caught errors.

Show solution
const caught = [new TypeError('a'), new Error('b'), new TypeError('c'), new RangeError('d')];
const counts = {};
for (const e of caught) counts[e.name] = (counts[e.name] || 0) + 1;
console.log(counts);

Output

{ TypeError: 2, Error: 1, RangeError: 1 }

Explanation: grouping by error.name quickly shows which kind of failure dominates a test run.

Keep Practising