Hone

Lessons · TypeScript · teaching the compiler what it is

A check the compiler remembers

A function returning x is string is a type predicate: when it returns true, the compiler treats the argument as a string in that branch.

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

typeof checks work once, inline. A guard lets you name the check, reuse it, and have the compiler narrow the type wherever it is used.

How to think about it

Write the runtime test, declare the return type as x is T, and use it in an if. The predicate is a promise you make: the compiler trusts it, so keep the test honest.

Worked example

function isStr(x: unknown): x is string { return typeof x === "string"; }
A type predicate: true narrows x to string for the caller.
function shoutIt(v: unknown): string { if (isStr(v)) { return v.toUpperCase(); } return ""; }
Inside the if, v is string, so toUpperCase compiles.
console.log(shoutIt("hi"), shoutIt(3));
HI and an empty string.

Your turn

A guard for numbers.

function isNum(x: unknown): x  number { return typeof x === "number"; }

The trap

A guard that lies, returning true for the wrong thing, is believed. The compiler checks the signature, not the logic inside.

Practise teaching the compiler what it is on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.