invariant-packages icon indicating copy to clipboard operation
invariant-packages copied to clipboard

Explain in README how ts-invariant is different than `invariant`

Open serhalp opened this issue 5 years ago • 3 comments

I might be missing something here, but I can't figure out why one would use ts-invariant over invariant.

The README states:

TypeScript implementation of invariant(condition, message).

and

This class is especially useful when writing TypeScript, because

invariant(typeof value === "number", "not a number");
console.log(value * 2); // type error!

doesn't tell TypeScript anything useful about value, whereas the following code can take full advantage of TypeScript's conditional type narrowing functionality:

if (typeof value !== "number") {
  throw InvariantError("not a number");
}
// TypeScript understands that value must be a number here:
console.log(value * 2);

But if using @types/invariant, this isn't true. The type definition here allows TS to narrow the type after an invariant() assertion.

So - what are the use cases for ts-invariant? Is the only difference that ts-invariant has built-in TS types whereas you need DefinitelyTyped annotations for invariant? Perhaps it's because this was only changed 4 months ago...

Thanks for any insights!

serhalp avatar Oct 31 '19 18:10 serhalp

As I see it, the advantages of this package over https://github.com/zertosh/invariant are:

  • Built-in types
  • Assertions in control flow analysis (when #12 will get merged)
  • Include rollup plugin that is tested
  • invariant.warn() and invariant.error()

Overall it seems a better integrated package if you are working with TypeScript

PowerKiKi avatar Apr 07 '20 02:04 PowerKiKi

@PowerKiKi Where do you stand now that #12 has not been merged since April.

Looks like https://yarnpkg.com/package/tiny-invariant also has built in types and supports type narrowing, for both flow and typescript...

chmac avatar Oct 12 '20 08:10 chmac

I don't have a strong opinion on the matter. I'm only here as a user of apollo-client. So this package is only my indirect dependency, and hence I have no say in whether I "use" it or not.

My sole purpose was to re-introduce strictNullChecks in apollo-client to reap the benefits in my app. It has been done since. Even though I assumed #12 was a requirement for it...

PowerKiKi avatar Oct 12 '20 09:10 PowerKiKi