invariant-packages
invariant-packages copied to clipboard
Explain in README how ts-invariant is different than `invariant`
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!
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()
andinvariant.error()
Overall it seems a better integrated package if you are working with TypeScript
@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...
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...