typescript: type narrowing with tiny-invariant

2022-01-05

 | 

~1 min read

 | 

158 words

I’ve written about type narrowing before in the context of type guards here and here.

The addition of tiny-invariant to the process is to throw an error if the type guard returns false.

export type PostMarkdownAttributes = {
  title: string
}

function isValidPostAttributes(
  attributes: any,
): attributes is PostMarkdownAttributes {
  return attributes?.title
}

const actualPost: unknown = { title: "My wicked title" }
const badPost: unknown = { data: "Lots of other stuff, but not title" }
invariant(isValidPostAttributes(actualPost), "Expected value to be a post") // The typeguard returns true, so Typescript knows `actualPost` is of type PostMarkdownAttributes.
invariant(isValidPostAttributes(badPost), "Expected value to be a post") // Error('Invariant violation: Expected value to be a post');

Normally with type guards, you do an if/then - this pattern would transform that into a try/catch with ease.

There’s more to explore here, but I like the error handling that comes with tiny invariant. It feels like a nice pattern to adopt.


Related Posts
  • Exploring Remix


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!