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

如何在JSDoc的@type标签中声明接受基类及其子类实例以解决PhpStorm类型校验警告

Fixing "Assigned expression type ValidatorRequired is not assignable to type Validator" Warning in PhpStorm

Got it, let's break down why you're seeing this warning and how to fix it quickly.

The root issue here is that PhpStorm can't recognize the inheritance relationship between your Validator base class and ValidatorRequired subclass because you haven't imported the Validator class into FormField.js. Without that import, the IDE treats Validator in your JSDoc @type tag as an unknown, untyped entity—so it can't confirm that ValidatorRequired (a known type) is compatible with it.

Here's how to fix it:

1. Import the Validator Base Class

Add an import for Validator at the top of FormField.js. This lets PhpStorm link up the type definitions properly:

import { Validator } from './Validator'; // Add this line
import { ValidatorRequired } from './ValidatorRequired';
export class FormField {
  // ... rest of your code
}

2. Confirm Your JSDoc Type Tag is Correct

Your existing @type tag for validators is actually correct:

/**
 * A collection of validators that should be run each time the field is validated.
 *
 * @type {Object.<string, Validator>}
 */
validators = {};

Since ValidatorRequired extends Validator, any subclass instance is safely assignable to a property typed as the base class. If you want to be more explicit (though not strictly necessary), you could also use Record<string, Validator> instead of Object.<string, Validator>—both work equally well in PhpStorm's type checking.

Why This Works

Once you import Validator, PhpStorm can see that ValidatorRequired inherits from it. It then understands that assigning a ValidatorRequired instance to a slot expecting Validator is perfectly valid (this is basic subtype polymorphism!).

Full Modified FormField.js Example

import { Validator } from './Validator';
import { ValidatorRequired } from './ValidatorRequired';
export class FormField {
    /**
     * Field's current value.
     *
     * @type {number|string}
     */
    value;
    /**
     * A collection of validators that should be run each time the field is validated.
     *
     * @type {Object.<string, Validator>}
     */
    validators = {};
    constructor({ required }) {
        this.required = Boolean(required);
        // No more warning here!
        this.validators.validatorRequired = new ValidatorRequired({ formField: this });
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 00:27:39