alexreardon / tiny-invariant

A tiny invariant function
MIT License
1.7k stars 48 forks source link

tiny-invariant throws on an empty string #174

Closed jasikpark closed 1 year ago

jasikpark commented 1 year ago

I use https://github.com/fram-x/assert-ts#check-condition for my simple code assertions, which allows me to narrow string | null | undefined to string w/o throwing an error on an empty string. tiny-invariant differs in that - is that intentional?

I find it confusing, since "" is still a string, but it does more clearly follow the if(!condition) pattern more directly, though you can achieve the same w/ assert-ts with assert(!!possiblyNullishOrEmptyString) to cause it to throw on an empty string

codesandbox.io/s/assert-v-s-tiny-invariant-z2w4gq

stof commented 1 year ago

tiny-invariant is explicitly documenting as checking whether the value passed as condition is falsy.

assert-ts has 2 signatures:

A check for nullish or a check for falsy will not be equivalent.

jasikpark commented 1 year ago

thx for the response - that's reasonable! i'll probably keep using ts-assert then 👍

alexreardon commented 1 year ago

From the description of this library:

An invariant function takes a value, and if the value is falsy then the invariant function will throw. If the value is truthy, then the function will not throw.

"" is falsy, and so will result in a throw.

If you don't want to throw on "" you could make your condition more explicit

invariant(typeof value === 'string' && value !== '');