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

Create custom scalar sub types to make $id's more specific. #11201

Open
joelharkes opened this issue Jan 16, 2025 · 2 comments
Open

Create custom scalar sub types to make $id's more specific. #11201

joelharkes opened this issue Jan 16, 2025 · 2 comments

Comments

@joelharkes
Copy link

joelharkes commented Jan 16, 2025

I'm working in a codebase right now that heavenly relies on passing $modelId's to the services.
It uses psalm to doctype which is already great! But since everything is the same scalar type it doesn't really stop you from making these mistakes:

function check(int $userId, int $roleId){...}

check($roleId, $userId);

It would be nice if you can make custom types that are somehow stricter.
Like this below is allowed, but would be nice it it actually throws an error that $x is not a RoleId

<?php

/**
 * @psalm-type UserId = int
 * @psalm-type RoleId = int
 * @param UserId $userId
 * @param RoleId $roleId
 */
function takesAnInt(int $userId, int $roleId): bool {
    
   return $userId > $roleId;
}

/** @var UserId $x */
$x = 2;
takesAnInt($x, $x);

I did some digging around but found no resources for this?

@joelharkes
Copy link
Author

see: https://psalm.dev/r/28737f8105

Copy link

I found these snippets:

https://psalm.dev/r/28737f8105
<?php

/**
 * @psalm-type UserId = int
 * @psalm-type RoleId = int
 * @param UserId $userId
 * @param RoleId $roleId
 */
function takesAnInt(int $userId, int $roleId): bool {
    
   return $userId > $roleId;
}

/** @var UserId $x */
$x = 2;
takesAnInt($x, $x);
Psalm output (using commit 765dcbf):

No issues!

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

No branches or pull requests

1 participant