bhylu.com

Advertisements

TypeScript Quiz

Use a short prediction exercise to separate runtime facts from compile-time promises. Explain each answer before opening the worked result.

Your brief

Will typeof null report null or object? Does readonly freeze an object at runtime? Can a function accepting unknown call a string method immediately? This fixture focuses on the first two questions. The numeric object has a readonly alias and a mutable alias to the same value, so a later change remains visible. For the third question, a runtime string guard is required before a string-only method becomes safe.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

Show the worked solution
lesson.ts

const stored = { packets: 4 };
const view: Readonly<{ packets: number }> = stored;
stored.packets = 2;
console.log(typeof null);
console.log(view.packets);

Expected result

object
2

JavaScript retains its historical typeof null result. The readonly view observes two because both references identify the same object; the modifier restricted assignments through view, not changes through every alias. These details explain why runtime validation and ownership decisions remain necessary in a typed program.

Try a change

Write a small validator that rejects null before reading a property. Add a test for an array as well as an ordinary object.

Advertisements