Hone

Lessons · TypeScript · types are gone at runtime

Types are gone at runtime

Interfaces and type annotations exist only for the compiler. After compiling, the browser runs plain JavaScript with no trace of them.

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

You cannot check typeof x === 'User' because User does not exist when the code runs. Data from the network needs a runtime check you write yourself, whatever its declared type.

How to think about it

Trust types for code you control; verify data from outside with a guard or a validation library at the boundary, then let the types take over.

Worked example

interface User { name: string }
Compile-time only.
const u: User = { name: "ada" };
A plain object.
console.log(typeof u);
object: at runtime an interface is nothing.
function isUser(x: unknown): x is User { return typeof x === "object" && x !== null && "name" in x; }
A runtime check you write yourself, because the type is gone.

Your turn

Assert the parsed JSON's type (which nothing checks at runtime).

const data = JSON.parse(text) as ;

The trap

as User is a promise to the compiler, not a check. JSON.parse(text) as User compiles for any JSON at all.

Practise types are gone at runtime on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.