Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

I've just read Absorbing unknown Into the Type Realm. It's a good read, check it out.

However I also learned an important difference between TypeScript type guards and assertion functions. And to be fair, I didn't even know assertion functions were a thing in TypeScript.

Let's look at a standard type guard.

ts
interface User {
name: string;
}
 
// standard type guard
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null && "name" in value;
}
 
// let's pretend JSON.parse is an unknown data source
const data = JSON.parse('{"name": "Stefan"}');
 
if (isUser(data)) {
data.name.toUpperCase(); // narrowed to User inside of condition scope
const data: User
}
 
data;
const data: any

If you receive data from an unknown source (most likely via fetch or HTTP), TypeScript doesn't know the types. To be on the safe side, you should bring in a validation library like Zod but if you only care about the types, a classic type guard might do the trick.

When you check the types above you see that thanks to the isUser type guard, data is of type User inside the condition scope. Great! But if you leave the scope you'll see that data is again back at any. Booh!

Now check this out!

ts
interface User {
name: string;
}
 
// assertion function
function assertIsUser(value: unknown): asserts value is User {
if (typeof value !== "object" || value === null || !("name" in value)) {
throw new Error("Expected a User");
}
}
 
// let's pretend JSON.parse is an unknown data source
const data = JSON.parse('{"name": "Stefan"}');
 
assertIsUser(data); // throws if not a User
 
data.name.toUpperCase(); // narrowed to User after assertion
const data: User

If you now change the type guard to be an assertion function with asserts value is User the type will be adjusted for the rest of the current scope. The contract is: if this function doesn't throw, apply the type to the current scope.

Good stuff!

If you enjoyed this article...

Join 6.5k readers and learn something new every week with Web Weekly.

Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles