Grokking TypeScript
Vote

0% completed

​

Type Guards

How can a compiler that never runs your program know that a value is a string on one line and a number on the next? The answer is that the compiler reads your if statements. Consider this function, which accepts a user id in either form.

function printId(id: string | number) { console.log(id.toUpperCase()); }
error TS2339: Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'.

A method call on a union must be valid for every member of the union, and numbers have no toUpperCase

.....

.....

.....

Like the course? Get enrolled and start learning!

Reading Progress

0%


Vote for new content