sindresorhus / is

Type check values
MIT License
1.68k stars 109 forks source link

Feature request: support optional checks / assertions #111

Open papb opened 4 years ago

papb commented 4 years ago

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

sindresorhus commented 4 years ago

I'm ok with assert.optional.string(foo), but I'll let the other maintainers share their opinion on this too.

papb commented 4 years ago

Ok. I will wait for the "go-ahead" before starting to work on a PR.

brandon93s commented 4 years ago

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)
}
papb commented 4 years ago

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: