Feature request: support optional checks / assertions
I would like to perform an assertion such as:
import {assert} from '@sindresorhus/is';
assert.optionalString(foo); // `foo` is narrowed to `string | undefined` now
The call signature itself may be different, perhaps assert.optional.string(foo) or assert.string(foo, { optional: true }).
I've noticed that ow supports optional checks but it does not perform TypeScript type assertion yet, so I looked here but apparently is does not support this either.
What do you think?
This might be a step towards (or inspiration to) solving https://github.com/sindresorhus/ow/issues/159
I'm ok with assert.optional.string(foo), but I'll let the other maintainers share their opinion on this too.
Ok. I will wait for the "go-ahead" before starting to work on a PR.
I'm not opposed to the optional modifier, but does it provide material benefits over assert.any:
const values = [undefined, '🦄']
for (const value of values) {
assert.any([is.undefined, is.string], value)
}
Hi @brandon93s, thank you for the idea, I admit I didn't think of using that construction.
However, I just tried it, and after calling assert.any([is.undefined, is.string], value), TypeScript still thinks value can be anything, instead of narrowing it down to string | undefined.
So I guess my issue could now be split in two:
- Request for improvement of
assert.anyTypeScript assertions - Request for a new
optionalmodifier that is just "syntatic sugar" for this construct withany+is.undefined. (The value for this "syntatic sugar" is debatable, I see, and I am not even sure of my own opinion on it anymore - I see now that the first bullet above is much more important to me)