Hone

Lessons · TypeScript · types promise, tests prove

Types promise a shape; a test proves a value

The compiler checks that percent returns a number. Which number, for which input, is a claim only a test can make, and a claim that fails throws with your message.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A typed codebase still ships wrong numbers. The type system cannot know that a quarter is 25, only that it is a number; a test is where that fact is written down.

How to think about it

Write the smallest assert you need: a check(ok, message) that throws. Claim the values that matter, with a message that says what was expected. Let the types handle shape and the tests handle truth.

Worked example

function check(ok: boolean, msg: string): void { if (!ok) throw new Error(msg); }
The smallest assert.
function share(part: number, whole: number): number { return whole === 0 ? 0 : Math.round((1000 * part) / whole) / 10; }
Typed: it returns a number.
check(share(1, 4) === 25, 'a quarter is 25');
Holds.
try { check(share(1, 3) === 33, 'a third rounds to 33.3'); } catch (e) { console.log('failed:', (e as Error).message); }
failed: a third rounds to 33.3
console.log('types said number; the tests say which number');
types said number; the tests say which number

Your turn

Claim the zero case.

check(share(5, 0) === , 'nothing out of nothing is 0');

The trap

Believing a green compile means the code is right. It means the shapes line up. The values are still yours to prove.

Practise types promise, tests prove on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.