Generics on Interfaces #10121
Answered
by
weirdan
bebetoalves
asked this question in
Q&A
Generics on Interfaces
#10121
-
Hello, I have an interface that implements a method which takes an array of format X and returns an array with the same format X. I tried using generics to express this, but apparently I can't do so because I'm getting "ImplementedReturnTypeMismatch" and "MoreSpecificImplementedParamType" errors. https://psalm.dev/r/5dd25daf35 <?php
interface Processor
{
/**
* @template TKey of array-key
* @template TValue
* @param array<TKey, TValue> $data
* @return array<TKey, TValue>
*/
public function process(array $data): array;
}
class QueryProcessor implements Processor
{
/**
* @param array{string, list<int>} $data
* @return array{string, list<int>}
*/
public function process(array $data): array
{
[$query, $parameters] = $data;
// some data process here
return [$query, $parameters];
}
}
class OutputProcessor implements Processor
{
/**
* @param list<string> $data
* @return list<string>
*/
public function process(array $data): array
{
// some data process here
return $data;
}
}
$query = new QueryProcessor();
$query->process(['query', [1,2,3]]);
$data = new OutputProcessor();
$data->process(['abc']); |
Beta Was this translation helpful? Give feedback.
Answered by
weirdan
Aug 17, 2023
Replies: 1 comment
-
You just need to lift the generic type param to the interface level: https://psalm.dev/r/c82c7ea6f2 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
bebetoalves
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You just need to lift the generic type param to the interface level: https://psalm.dev/r/c82c7ea6f2