You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Larastan v2中findOrFail返回类型错误的解决疑问

Larastan v2 等级7下findOrFail()返回值类型提示报错处理

问题场景

现有如下方法,通过findOrFail()查询并返回模型实例:

function getRecord(string $id): MyModel
{
    return MyModel::query()->findOrFail($id);
}

使用Larastan v2等级7检测时,触发类型不匹配错误:

53     Method                                                               
       App\Actions\MyModelAction\MyAction::getRecord()    
       should return App\Models\MyModel but returns                     
       App\Models\MyModel|Illuminate\Database\Eloquent\Collection<int,  
       App\Models\MyModel>.  

当前采用的临时解决方法是引入中间变量并添加类型注释:

function getRecord(string $id): MyModel
{
    /** @var MyModel $result */
    $result = MyModel::query()->findOrFail($id);
    return $result;
}

解决方案:无需中间变量,直接添加内联类型注释

可以直接在return语句中对findOrFail()的返回值添加内联类型注释,无需定义额外变量,即可通过Larastan等级7检测:

function getRecord(string $id): MyModel
{
    return /** @var MyModel */ MyModel::query()->findOrFail($id);
}

原理说明

Larastan在高等级检测下,会将findOrFail()的返回值推断为「模型实例|集合」的联合类型(因为该方法支持传入数组ID返回集合),即便当前方法参数是string类型,Larastan的类型推断未完全关联参数类型进行窄化。通过内联的/** @var MyModel */注释,直接告诉Larastan该表达式的返回值为单一模型实例,从而通过类型检测。这种方式同样适用于复杂场景,比如直接返回函数执行后的查询结果,保持代码简洁。

内容的提问来源于stack exchange,提问作者Mistre83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 20:33:11