is icon indicating copy to clipboard operation
is copied to clipboard

Feature request: support optional checks / assertions

Open papb opened this issue 5 years ago • 4 comments

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

papb avatar May 12 '20 20:05 papb

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

sindresorhus avatar May 16 '20 10:05 sindresorhus

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

papb avatar May 16 '20 20:05 papb

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)
}

brandon93s avatar May 18 '20 02:05 brandon93s

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.any TypeScript assertions
  • Request for a new optional modifier that is just "syntatic sugar" for this construct with any + 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)

papb avatar May 18 '20 02:05 papb