Skip to content

Register to Vote πŸ‡ΊπŸ‡Έ

Type Predicates in TypeScript

TypeScript is a nice idea, but I haven't fully figured it out...

A very important bit of TypeScript that I just learned about is type predicates. An example you can see is from the svelte prettier plugin:

/**
 * Determines whether or not given node
 * is the root of the Svelte AST.
 */
export function isASTNode(n: any): n is ASTNode {
  return n && n.__isRoot;
}

This allows you to communicate to the TypeScript compiler in an if statement using the above function what the type of n is, while also still being functional in vanilla JavaScript.

if (isASTNode(node)) {
  // TypeScript allows accessing properties of `ASTNode` objects here, since it now knows that `node` is an `ASTNode`.
} else {
  // TypeScript knows that `node` is not an ASTNode in this block, since it failed the check.
}
// After the if statement and type guard (`isASTNode()`), TypeScript no longer knows whether `node` is an `ASTNode`.

This is great! Even better, typescript 4.4 will have improved support for type predicates: Microsoft Devblog: Announcing TypeScript 4.4 Beta. One of the big advantages will be that TypeScript will search constants that are tested in if statements for type guards, so if you instead had run,

const isNodeASTNode = isASTNode(node);
if(isNodeASTNode) { ...

then instead of erroring like previous versions, since the compiler threw away the type guard information when it was put in a variable, it will look for that information now.

Something else that's interesting is the postfix operator ! that lets you assert a variable as non-null to the typescript compiler, I'm sure that comes in handy when the compiler is being a lil dumb!

Maybe there'll be more posts about TypeScript. Who knows!