Psalm: FeatureRequest: Would it be possible to add either support for union types to `@psalm-assert` or multiple `@psalm-assert` per method

Created on 4 Jul 2019  路  7Comments  路  Source: vimeo/psalm

It would be nice to have it to implement https://github.com/webmozart/assert nullOrX methods.

Most helpful comment

@zerkms I implemented union types - the nullable type ?Foo is just a shorthand for the union type null|Foo.

All 7 comments

After exploring more it looks like just nullable types ?string etc would be enough. I'll still leave this request though.

Ok, it looks like it does not work though

<?php

namespace Webmozart\Assert\StaticAnalysis\AssertString;

/**
 * @psalm-assert ?string $value
 * @param mixed $value
 * @param string $message
 */
function string($value, $message = ''): void
{
}

/**
 * @param mixed $value
 * @return string
 */
function consume2($value): ?string
{
    string($value);

    return $value;
}
ERROR: InvalidReturnType - static-analysis/assert-string.php:28:12 - The declared return type 'string' for Webmozart\Assert\StaticAnalysis\AssertString\consume2 is incorrect, got 'Webmozart\Assert\StaticAnalysis\AssertString\'
 * @return string


ERROR: InvalidReturnStatement - static-analysis/assert-string.php:34:12 - The type 'Webmozart\Assert\StaticAnalysis\AssertString\' does not match the declared return type 'string' for Webmozart\Assert\StaticAnalysis\AssertString\consume2
    return $value;

And it's alright if no namespace is specified.

@muglug I'm not very familiar with the code base, but does it mean you implemented both nullable and union types?!

@zerkms I implemented union types - the nullable type ?Foo is just a shorthand for the union type null|Foo.

@muglug There are still issues with shorthand nullable assertions in namespaces:
https://psalm.dev/r/a03338b9dc

Works fine in global namespace, or when using null|string instead of ?string.

Also not sure if it was a support of just 2 types in a union but null|string|number also fails: https://psalm.dev/r/8698d7513f

I explored the corresponding assertion and @param parsing methods - why assertion is so unique? Cannot the same code used to parse typing in @param be reused (that is guaranteed to support everything correctly already)

@weirdan ?string is not yet supported, but null|string is.

@zerkms number is not a valid assertion - but numeric is

Was this page helpful?
0 / 5 - 0 ratings