Skip to content

How to specify correct return type of function that queries database? #7885

Answered by theodorejb
theodorejb asked this question in Q&A
Discussion options

You must be logged in to vote

I found a way to do it using the @psalm-type and @var annotations:

/**
 * @psalm-type UserList = list<array{id: int, name: string}>
 * @return UserList
 */
function getUsers(mysqli $db, string $role): array
{
    /** @var UserList */
    return query($db, "SELECT id, name FROM users WHERE role = ?", [$role]);
}

It's a little more boilerplate-y than I would like, but it works!

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@weirdan
Comment options

@theodorejb
Comment options

@M1ke
Comment options

Answer selected by theodorejb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants