DEV Community

Discussion on: Guards using invariant in JS

Collapse
 
shuckster profile image
Conan

If you use TypeScript, a useful version of invariant is tiny-invariant:

import invariant from 'tiny-invariant';

const title: any = getValueFromSomewhereUntrusted();
// At this point TS will type 'title' as 'any'

invariant(typeof title === 'string');
// At this point TS will type 'title' as 'string'
Enter fullscreen mode Exit fullscreen mode

Because of the use of asserts at this source-line you're dropping a hint to the type-engine about what you've called invariant on.

Collapse
 
fromaline profile image
Nick

Yeah, you're right. It's so simple yet useful difference.
Thanks for adding value!