Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: support optional checks / assertions #111

Open
papb opened this issue May 12, 2020 · 4 comments
Open

Feature request: support optional checks / assertions #111

papb opened this issue May 12, 2020 · 4 comments

Comments

@papb
Copy link
Contributor

papb commented May 12, 2020

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 sindresorhus/ow#159

@sindresorhus
Copy link
Owner

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

@papb
Copy link
Contributor Author

papb commented May 16, 2020

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

@brandon93s
Copy link
Collaborator

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
Copy link
Contributor Author

papb commented May 18, 2020

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants