0

在我的代码中,我创建了一个这样的 EventFactory:

private array $events = [
    'post_created' => PostCreatedEvent::class,
    'exercise_executed' => ExerciseExecutedEvent::class,
];

public function fromTopicAndData(string $topic, array $data) : Event
{
    if (! array_key_exists($topic, $this->events)) {
        throw new Exception('Invalid Topic');
    }

    $event = ($this->events)[$topic];
    return $event::createFromData($data);
}

PostCreatedEvent和ExerciseExecutedEvent扩展了一个抽象类Event

你能告诉我是否有办法以不从 Psalm 接收错误的方式注释数组?

4

1 回答 1

2

假设Event类声明createFromData()了方法,下面的 docblock 应该可以解决问题:

/** @var array<string, class-string<Event>> */
private array $events = [
    'post_created' => PostCreatedEvent::class,
    'exercise_executed' => ExerciseExecutedEvent::class,
];

现场演示:https ://psalm.dev/r/da11fc8d8c

于 2021-12-21T17:53:45.017 回答