如何在JSDoc的@type标签中声明接受基类及其子类实例以解决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

