psl icon indicating copy to clipboard operation
psl copied to clipboard

Type\not_null()

Open rodnaph opened this issue 3 years ago • 2 comments

Is your feature request related to a problem? Please describe.

Quite often I find myself using Type\instance_of to assert values are not null, for example...

/** @var null|Foo $x */
$x = getSomeValueOrAccessAPropertyOrMethodEtc();

$x = Type\instance_of(Foo::class)->assert($x);

Here I'm essentially duplicating the expected type (Foo::class), because it's usually already declared on the property/method etc... but is nullable.

Describe the solution you'd like

It would be more concise to be able to say...

$x = Type\not_null()->assert($x);

Which would assert that $x is Foo and not null|Foo.

Describe alternatives you've considered

I've presented my current solution for this above, I'm not aware of any other features of PSL which could be used here (apologies if I've missed something).

rodnaph avatar Jul 12 '22 12:07 rodnaph

There is Psl\invariant:

invariant($x !== null, 'must not be null');

And indeed - I also personally prefer to use not null assertion other than it should be of this type.

zerkms avatar Jul 25 '22 22:07 zerkms

this won't be possible, as psalm doesn't have a type that includes everything but not null 🤔

azjezz avatar Dec 19 '22 20:12 azjezz

The not_null type exists - yet there is no type narrowing possible in psalm (without a plugin). Is that sufficient or should we keep this open @azjezz ?

veewee avatar Apr 04 '24 11:04 veewee

we could close this issue, and open a new one in the plugin repository to add support for type narrowing when Type\not_null() is used?

wdyt @veewee ?

azjezz avatar Apr 04 '24 11:04 azjezz