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

Annotate "insert element" operation on TKeyedArray #4193

Open
doggor opened this issue Sep 16, 2020 · 4 comments
Open

Annotate "insert element" operation on TKeyedArray #4193

doggor opened this issue Sep 16, 2020 · 4 comments

Comments

@doggor
Copy link

doggor commented Sep 16, 2020

I have a function that accept an TKeyedArray and insert a specific element into it. For example, given a input $arr which is in type of @template T of array{id: int} , after having operation like $arr['baz'] = 'baz'; the output should becomes T & array{'baz':string}.

https://psalm.dev/r/ef60918b5a

I found a similar issue #3339 that describes a more general situation, but don't know if there is a solution for this case.

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/ef60918b5a
<?php

/**
 * @template T of array{id: int}
 *
 * @param T $arr
 * @param-out T&array{bar: string} $arr
 * @return void
 **/
function addBar(array &$arr): void {
    $arr['bar'] = 'bar';
}

$arr1 = ['id' => 1, 'foo' => 'foo'];
$arr2 = ['id' => 2, 'baz' => 'baz'];

addBar($arr1);
addBar($arr2);
Psalm output (using commit dda013d):

ERROR: InvalidDocblock - 10:1 - Intersection types must be all objects or all object-like arrays, Psalm\Type\Atomic\TKeyedArray provided in docblock for addBar

ERROR: ReferenceConstraintViolation - 10:24 - Variable $arr is limited to values of type T:fn-addbar as array{id: int} because it is passed by reference, (T:fn-addbar as array{id: int})|array{bar: string(bar)} type found. Use @param-out to specify a different output type

@weirdan weirdan added the bug label Sep 16, 2020
@weirdan
Copy link
Collaborator

weirdan commented Sep 16, 2020

At least the message is wrong, as TKeyedArray is what previously was called object-like array.

@doggor doggor changed the title [Question] How to annotate "insert element" operation on object-like array Annotate "insert element" operation on TKeyedArray Sep 17, 2020
@weirdan
Copy link
Collaborator

weirdan commented Sep 17, 2020

I was referring to the

ERROR: InvalidDocblock - 10:1 - Intersection types must be all objects or all object-like arrays, Psalm\Type\Atomic\TKeyedArray provided in docblock for addBar

It's self-contradicting, as TKeyedArray is object-like array.

@orklah
Copy link
Collaborator

orklah commented Oct 9, 2021

The message was changed, so this is no longer a bug, rather a enhancement

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

Successfully merging a pull request may close this issue.

3 participants