# Eslint Plugin Jsdoc > --- ## Advanced * [AST and Selectors](#user-content-advanced-ast-and-selectors) * [`contexts` format](#user-content-advanced-ast-and-selectors-contexts-format) * [Discovering available AST definitions](#user-content-advanced-ast-and-selectors-discovering-available-ast-definitions) * [Uses/Tips for AST](#user-content-advanced-ast-and-selectors-uses-tips-for-ast) * [Creating your own rules](#user-content-advanced-creating-your-own-rules) * [Forbidding structures](#user-content-advanced-creating-your-own-rules-forbidding-structures) * [Preferring type structures](#user-content-advanced-creating-your-own-rules-preferring-type-structures) ### AST and Selectors For various rules, one can add to the environments to which the rule applies by using the `contexts` option. This option works with [ESLint's selectors](https://eslint.org/docs/developer-guide/selectors) which are [esquery](https://github.com/estools/esquery/#readme) expressions one may use to target a specific node type or types, including subsets of the type(s) such as nodes with certain children or attributes. These expressions are used within ESLint plugins to find those parts of your files' code which are of interest to check. However, in `eslint-plugin-jsdoc`, we also allow you to use these selectors to define additional contexts where you wish our own rules to be applied. #### contexts format While at their simplest, these can be an array of string selectors, one can also supply an object with `context` (in place of the string) and one of two properties: 1. For `require-jsdoc`, there are also `inlineCommentBlock` and `minLineCount` properties. See that rule for details. 1. For `no-missing-syntax` and `no-restricted-syntax`, there is also a `message` property which allows customization of the message to be shown when the rule is triggered. 1. For `no-missing-syntax`, there is also a `minimum` property. See that rule. 1. For other rules, there is a `comment` property which adds to the `context` in requiring that the `comment` AST condition is also met, e.g., to require that certain tags are present and/or or types and type operators are in use. Note that this AST (either for `Jsdoc*` or `JsdocType*` AST) has not been standardized and should be considered experimental. Note that this property might also become obsolete if parsers begin to include JSDoc-structured AST. A [parser](https://github.com/brettz9/jsdoc-eslint-parser/) is available which aims to support comment AST as a first class citizen where comment/comment types can be used anywhere within a normal AST selector but this should only be considered experimental. When using such a parser, you need not use `comment` and can just use a plain string context. The determination of the node on which the comment is attached is based more on actual location than semantics (e.g., it will be attached to a `VariableDeclaration` if above that rather than to the `FunctionExpression` it is fundamentally describing). See [@es-joy/jsdoccomment](https://github.com/es-joy/jsdoccomment) for the precise structure of the comment (and comment type) nodes. #### Discovering available AST definitions To know all of the AST definitions one may target, it will depend on the [parser](https://eslint.org/docs/user-guide/configuring#specifying-parser) you are using with ESLint (e.g., `espree` is the default parser for ESLint, and this follows [EStree AST](https://github.com/estree/estree) but to support the the latest experimental features of JavaScript, one may use `@babel/eslint-parser` or to be able to have one's rules (including JSDoc rules) apply to TypeScript, one may use `typescript-eslint`, etc. So you can look up a particular parser to see its rules, e.g., browse through the [ESTree docs](https://github.com/estree/estree) as used by Espree or see ESLint's [overview of the structure of AST](https://eslint.org/docs/developer-guide/working-with-custom-parsers#the-ast-specification). However, it can sometimes be even more helpful to get an idea of AST by just providing some of your JavaScript to the wonderful [AST Explorer](https://astexplorer.net/) tool and see what AST is built out of your code. You can set the tool to the specific parser which you are using. For comment AST, see the [@es-joy/jsdoccomment demo](https://es-joy.github.io/jsdoccomment/demo/) or if you are only interested in type AST, see the [jsdoc-type-pratt-parser demo](https://jsdoc-type-pratt-parser.github.io/jsdoc-type-pratt-parser/). #### Uses/Tips for AST And if you wish to introspect on the AST of code within your projects, you can use [eslint-plugin-query](https://github.com/brettz9/eslint-plugin-query). Though it also works as a plugin, you can use it with its own CLI, e.g., to search your files for matching esquery selectors, optionally showing it as AST JSON. Tip: If you want to more deeply understand not just the resulting AST tree structures for any given code but also the syntax for esquery selectors so that you can, for example, find only those nodes with a child of a certain type, you can set the "Transform" feature to ESLint and test out esquery selectors in place of the selector expression (e.g., replace `'VariableDeclaration > VariableDeclarator > Identifier[name="someVar"]'` as we have [here](https://astexplorer.net/#/gist/71a93130c19599d6f197bddb29c13a59/latest)) to the selector you wish so as to get messages reported in the bottom right pane which match your [esquery](https://github.com/estools/esquery/#readme) selector). ### Creating your own rules #### Forbidding structures Although `jsdoc/no-restricted-syntax` is available for restricting certain syntax, it comes at a cost that, no matter how many restrictions one adds, one can only disable a single restriction by disabling them all. With the `extraRuleDefinitions.forbid` option, one can add information that is used to create extra individual rules forbidding specific structures, and these rules can then be selectively enabled and optionally disabled on a case-by-case basis. For each `forbid` key, add the name of the context (this will be appended to `forbid-` to decide the name of the rule, so with "Any" as the key, the rule created will be `forbid-Any`). Then provide an optional `description` and `url` keys (which will be used for the created rule's `meta.docs` `description` and `url` properties) and the `contexts` array. See the `jsdoc/restricted-syntax` rule for more details. ```js import {jsdoc} from 'eslint-plugin-jsdoc'; export default [ jsdoc({ config: 'flat/recommended', extraRuleDefinitions: { forbid: { Any: { contexts: [ { comment: 'JsdocBlock:has(JsdocTypeName[value="any"])', context: 'any', message: '`any` is not allowed; use a more specific type', }, ], description: 'Forbids `any` usage', url: 'https://example.com/docs-for-my-any-rule/' }, Function: { contexts: [ { comment: 'JsdocBlock:has(JsdocTypeName[value="Function"])', context: 'any', message: '`Function` is not allowed; use a more specific type', }, ], }, }, }, // Be sure to enable the rules as well rules: { 'jsdoc/forbid-Any': [ 'error', ], 'jsdoc/forbid-Function': [ 'warn', ], }, }), ]; ``` Now you can selectively disable the rules you have created. In the following, because of the individual disable directive, only the `Function` rule will be triggered (as a warning since its rule was set to "warn"): ```js /* eslint-disable jsdoc/forbid-Any */ /** * @param {any} abc Test * @param {Function} def Test2 */ export const a = (abc, def) => { b(5, abc, def); }; /* eslint-enable jsdoc/forbid-Any */ ``` #### Preferring type structures When the structures in question are types, a disadvantage of the previous approach is that one cannot perform replacements nor can one distinguish between parent and child types for a generic. If targeting a type structure, you can use `extraRuleDefinitions.preferTypes`. While one can get this same behavior using the `preferredTypes` setting, the advantage of creating a rule definition is that handling is distributed not to a single rule (`jsdoc/check-types`), but to an individual rule for each preferred type (which can then be selectively enabled and disabled). ```js import {jsdoc} from 'eslint-plugin-jsdoc'; export default [ jsdoc({ config: 'flat/recommended', extraRuleDefinitions: { preferTypes: { // This key will be used in the rule name promise: { description: 'This rule disallows Promises without a generic type', overrideSettings: { // Uses the same keys are are available on the `preferredTypes` settings // This key will indicate the type node name to find Promise: { // This is the specific error message if reported message: 'Add a generic type for this Promise.', // This can instead be a string replacement if an auto-replacement // is desired replacement: false, // If `true`, this will check in both parent and child positions unifyParentAndChildTypeChecks: false, }, }, url: 'https://example.com/Promise-rule.md', }, }, }, rules: { // Don't forget to enable the above-defined rules 'jsdoc/prefer-type-promise': [ 'error', ], } }) ``` --- ## Processors Normally JavaScript content inside JSDoc tags is not discoverable by ESLint. `eslint-plugin-jsdoc` offers a processor which allows ESLint to parse `@example` and other tag text for JavaScript so that it can be linted. The approach below works in ESLint 9. For ESLint 7, please see our [`check-examples`](./rules/check-examples.md#readme) rule. The approach requires that we first indicate the JavaScript files that will be checked for `@example` tags. ```js import {getJsdocProcessorPlugin} from 'eslint-plugin-jsdoc'; export default [ { files: ['**/*.js'], plugins: { examples: getJsdocProcessorPlugin({ // Enable these options if you want the `someDefault` inside of the // following to be checked in addition to `@example`: // 1. `@default someDefault` // 2. `@param [val=someDefault]`, // 3. `@property [val=someDefault]` // checkDefaults: true, // checkParams: true, // checkProperties: true }) }, processor: 'examples/examples' }, ]; ``` Now you can target the JavaScript inside these `@example` or default blocks by the following: ```js // Since `@example` JavaScript often follows the same rules as JavaScript in // Markdown, we use the `.md` extension as the parent by default: { files: ['**/*.md/*.js'], rules: { // Enable or disable rules for `@example` JavaScript here } }, { files: ['**/*.jsdoc-defaults', '**/*.jsdoc-params', '**/*.jsdoc-properties'], rules: { // Enable or disable rules for `@default`, `@param`, or `@property` // JavaScript here } } ``` Alternatively you can just use our built-in configs which do the above for you: ```js import jsdoc from 'eslint-plugin-jsdoc'; export default [ ...jsdoc.configs.examples // Or for @default, @param and @property default expression processing // ...jsdoc.configs['default-expressions'] // Or for both, use: // ...jsdoc.configs['examples-and-default-expressions'], ]; ``` These configs also disable certain rules which are rarely useful in an `@example` or default context. For example both kinds disable the rule `no-unused-vars` since it is common for short demos to show how to declare a variable, but not how to use it. Default expressions are usually even more strict as they are typically not going to form a whole statement, but just an expression. With the following: ```js /** * @param [abc=someDefault] */ function quux (abc) {} ``` ...`someDefault` can be checked as JavaScript, but we don't want rules like `no-unused-expressions` firing, since we're not going to use the expression here. For defaults, a couple rules are enabled which are usually useful: - `quotes` - Set to `double`. It is more common within this context for double quotes to be used. - `semi` - Set to 'never' since a semi-colon is not desirable in this context. ### Use with TypeScript ```js import {getJsdocProcessorPlugin} from 'eslint-plugin-jsdoc'; import ts, { parser as typescriptEslintParser, } from 'typescript-eslint'; export default [ { files: [ '**/*.ts', ], languageOptions: { // Allows normal processing of TS files parser: typescriptEslintParser }, // Apply the processor to these TypeScript files name: 'jsdoc/examples/processor', plugins: { examples: getJsdocProcessorPlugin({ // Allows processor to parse TS files for @example tags parser: typescriptEslintParser, // In order to avoid the default of processing our examples // as *.js files, we indicate the inner blocks are TS. // This allows us to target the examples as TS files, as // we do below. matchingFileName: 'dummy.md/*.ts', // If you only want to match @example content within fenced // Markdown blocks, use: // exampleCodeRegex: "^```ts([\\s\\S]*)```\\s*$" }), }, processor: 'examples/examples' }, // Apply your TypeScript config ...ts.configs.recommended, { // Target the @example blocks within TypeScript files: [ // `**/*.ts` could also work if you want to share this config // with other non-@example TypeScript '**/*.md/*.ts', ], name: 'jsdoc/examples/rules', languageOptions: { // Allows @example itself to use TS parser: typescriptEslintParser, }, rules: { // Add the rules you want to apply to @example here 'no-extra-semi': 'error', // disable problematic rules here, e.g., // ...jsdoc.configs.examples[1].rules // Due to https://github.com/gajus/eslint-plugin-jsdoc/issues/1377 , // `typescript-eslint` type-checked rules must currently be disbaled ...ts.configs.disableTypeChecked.rules } } ]; ``` ### Options #### checkDefaults Whether to check `@default` tags. Defaults to `false`. #### checkExamples Whether to check `@example` tags. Defaults to `true`. #### checkParams Whether to check `@param [name=someDefaultValue]` content. Defaults to `false`. #### checkProperties Whether to check `@property [name=someDefaultValue]` content. Defaults to `false`. #### captionRequired Whether to require the JSDoc `` content inside the `@example` tag. Defaults to `false`. #### paddedIndent The number of spaces to assume at the beginning of each line. Defaults to 0. Should only have an effect on whitespace-based rules. #### matchingFileName #### matchingFileNameDefaults #### matchingFileNameParams #### matchingFileNameProperties See the [`check-examples`](./rules/check-examples.md#readme) option of the same name. #### exampleCodeRegex and rejectExampleCodeRegex See the [`check-examples`](./rules/check-examples.md#readme) option of the same name. #### allowedLanguagesToProcess This is an array which will narrow the allowable languages of fenced blocks down to those within the array. Set to `false` to ensure all present languages (not excluded by any `exampleCodeRegex` and `rejectExampleCodeRegex` options) will be processed. Defaults to `['js', 'ts', 'javascript', 'typescript']`. #### sourceType Whether to use "script" or "module" with the parser. Defaults to `"module"`. #### parser An alternative parser which has a `parseForESLint` method and returns the AST on the `ast` property (like `typescript-eslint`). Defaults to using ESLint's Espree parser. --- # check-access * [Context and settings](#user-content-check-access-context-and-settings) * [Failing examples](#user-content-check-access-failing-examples) * [Passing examples](#user-content-check-access-passing-examples) Checks that `@access` tags use one of the following values: - "package", "private", "protected", "public" Also reports: - Mixing of `@access` with `@public`, `@private`, `@protected`, or `@package` on the same doc block. - Use of multiple instances of `@access` (or the `@public`, etc. style tags) on the same doc block. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`@access`| |Recommended|true| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @access foo */ function quux (foo) { } // Message: Missing valid JSDoc @access level. /** * @access foo */ function quux (foo) { } // Settings: {"jsdoc":{"ignorePrivate":true}} // Message: Missing valid JSDoc @access level. /** * @accessLevel foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"access":"accessLevel"}}} // Message: Missing valid JSDoc @accessLevel level. /** * @access */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"access":false}}} // Message: Unexpected tag `@access` class MyClass { /** * @access */ myClassField = 1 } // Message: Missing valid JSDoc @access level. /** * @access public * @public */ function quux (foo) { } // Message: The @access tag may not be used with specific access-control tags (@package, @private, @protected, or @public). /** * @access public * @access private */ function quux (foo) { } // Message: At most one access-control tag may be present on a JSDoc block. /** * @access public * @access private */ function quux (foo) { } // Settings: {"jsdoc":{"ignorePrivate":true}} // Message: At most one access-control tag may be present on a JSDoc block. /** * @public * @private */ function quux (foo) { } // Message: At most one access-control tag may be present on a JSDoc block. /** * @public * @private */ function quux (foo) { } // Settings: {"jsdoc":{"ignorePrivate":true}} // Message: At most one access-control tag may be present on a JSDoc block. /** * @public * @public */ function quux (foo) { } // Message: At most one access-control tag may be present on a JSDoc block. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ function quux (foo) { } /** * @access public */ function quux (foo) { } /** * @accessLevel package */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"access":"accessLevel"}}} class MyClass { /** * @access private */ myClassField = 1 } /** * @public */ function quux (foo) { } /** * @private */ function quux (foo) { } // Settings: {"jsdoc":{"ignorePrivate":true}} ```` --- # check-alignment * [Fixer](#user-content-check-alignment-fixer) * [Options](#user-content-check-alignment-options) * [`innerIndent`](#user-content-check-alignment-options-innerindent) * [Context and settings](#user-content-check-alignment-context-and-settings) * [Failing examples](#user-content-check-alignment-failing-examples) * [Passing examples](#user-content-check-alignment-passing-examples) Reports invalid alignment of JSDoc block asterisks. ## Fixer Fixes alignment. ## Options A single options object has the following properties. ### innerIndent Set to 0 if you wish to avoid the normal requirement for an inner indentation of one space. Defaults to 1 (one space of normal inner indentation). ## Context and settings ||| |---|---| |Context|everywhere| |Tags|N/A| |Recommended|true| |Options|`innerIndent`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {Number} foo */ function quux (foo) { // with spaces } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { // with tabs } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { // with spaces } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { // with spaces } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo */ function quux (foo) { } // Message: Expected JSDoc block to be aligned. /** * A JSDoc not attached to any node. */ // Message: Expected JSDoc block to be aligned. class Foo { /** * Some method * @param a */ quux(a) {} } // Message: Expected JSDoc block to be aligned. export const myVar = {/** * This is JSDoc */ myProperty: 'hello' } // Message: Expected JSDoc block to be aligned. /** * @param {Number} foo * @access private */ function quux (foo) { // with spaces } // "jsdoc/check-alignment": ["error"|"warn", {"innerIndent":0}] // Message: Expected JSDoc block to be aligned. /** Some desc. @param {Number} foo @access private */ function quux (foo) { // with spaces } // "jsdoc/check-alignment": ["error"|"warn", {"innerIndent":0}] // Message: Expected JSDoc block to be aligned. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * Desc * * @param {Number} foo */ function quux (foo) { } /** * Desc * * @param {{ foo: Bar, bar: Baz * }} foo * */ function quux (foo) { } /* <- JSDoc must start with 2 stars. * So this is unchecked. */ function quux (foo) {} /** * @param {Number} foo * @private */ function quux (foo) { // with spaces } // Settings: {"jsdoc":{"ignorePrivate":true}} /** * @param {Number} foo * @access private */ function quux (foo) { // with spaces } // Settings: {"jsdoc":{"ignorePrivate":true}} /** * @param {Number} foo * @access private */ function quux (foo) { // with spaces } // "jsdoc/check-alignment": ["error"|"warn", {"innerIndent":0}] /** Some desc. @param {Number} foo @access private */ function quux (foo) { // with spaces } // "jsdoc/check-alignment": ["error"|"warn", {"innerIndent":0}] ```` --- # check-examples * [Options](#user-content-check-examples-options) * [`captionRequired`](#user-content-check-examples-options-captionrequired) * [`exampleCodeRegex` and `rejectExampleCodeRegex`](#user-content-check-examples-options-examplecoderegex-and-rejectexamplecoderegex) * [`paddedIndent`](#user-content-check-examples-options-paddedindent) * [`reportUnusedDisableDirectives`](#user-content-check-examples-options-reportunuseddisabledirectives) * [Options for Determining ESLint Rule Applicability (`allowInlineConfig`, `noDefaultExampleRules`, `matchingFileName`, `configFile`, `checkEslintrc`, and `baseConfig`)](#user-content-check-examples-options-for-determining-eslint-rule-applicability-allowinlineconfig-nodefaultexamplerules-matchingfilename-configfile-checkeslintrc-and-baseconfig) * [Rules Disabled by Default Unless `noDefaultExampleRules` is Set to `true`](#user-content-check-examples-options-for-determining-eslint-rule-applicability-allowinlineconfig-nodefaultexamplerules-matchingfilename-configfile-checkeslintrc-and-baseconfig-rules-disabled-by-default-unless-nodefaultexamplerules-is-set-to-true) * [Options for checking other than `@example` (`checkDefaults`, `checkParams`, or `checkProperties`)](#user-content-check-examples-options-for-determining-eslint-rule-applicability-allowinlineconfig-nodefaultexamplerules-matchingfilename-configfile-checkeslintrc-and-baseconfig-options-for-checking-other-than-example-checkdefaults-checkparams-or-checkproperties) * [Context and settings](#user-content-check-examples-context-and-settings) * [Failing examples](#user-content-check-examples-failing-examples) * [Passing examples](#user-content-check-examples-passing-examples) > **NOTE**: This rule only works in ESLint 7. For ESLint 9, please see our > [processors](../processors.md) section. Ensures that (JavaScript) samples within `@example` tags adhere to ESLint rules. Also has options to lint the default values of optional `@param`/`@arg`/`@argument` and `@property`/`@prop` tags or the values of `@default`/`@defaultvalue` tags. ## Options The options below all default to no-op/`false` except as noted. ### captionRequired JSDoc specs use of an optional `` element at the beginning of `@example`. The option `captionRequired` insists on a `` being present at the beginning of any `@example`. Used only for `@example`. ### exampleCodeRegex and rejectExampleCodeRegex JSDoc does not specify a formal means for delimiting code blocks within `@example` (it uses generic syntax highlighting techniques for its own syntax highlighting). The following options determine whether a given `@example` tag will have the `check-examples` checks applied to it: * `exampleCodeRegex` - Regex which whitelists lintable examples. If a parenthetical group is used, the first one will be used, so you may wish to use `(?:...)` groups where you do not wish the first such group treated as one to include. If no parenthetical group exists or matches, the whole matching expression will be used. An example might be ````"^```(?:js|javascript)([\\s\\S]*)```\s*$"```` to only match explicitly fenced JavaScript blocks. Defaults to only using the `v` flag, so to add your own flags, encapsulate your expression as a string, but like a literal, e.g., ````/```js.*```/gi````. Note that specifying a global regular expression (i.e., with `g`) will allow independent linting of matched blocks within a single `@example`. * `rejectExampleCodeRegex` - Regex blacklist which rejects non-lintable examples (has priority over `exampleCodeRegex`). An example might be ```"^`"``` to avoid linting fenced blocks which may indicate a non-JavaScript language. See `exampleCodeRegex` on how to add flags if the default `v` is not sufficient. If neither is in use, all examples will be matched. Note also that even if `captionRequired` is not set, any initial `` will be stripped out before doing the regex matching. ### paddedIndent This integer property allows one to add a fixed amount of whitespace at the beginning of the second or later lines of the example to be stripped so as to avoid linting issues with the decorative whitespace. For example, if set to a value of `4`, the initial whitespace below will not trigger `indent` rule errors as the extra 4 spaces on each subsequent line will be stripped out before evaluation. ```js /** * @example * anArray.filter((a) => { * return a.b; * }); */ ``` Only applied to `@example` linting. ### reportUnusedDisableDirectives If not set to `false`, `reportUnusedDisableDirectives` will report disabled directives which are not used (and thus not needed). Defaults to `true`. Corresponds to ESLint's [`--report-unused-disable-directives`](https://eslint.org/docs/user-guide/command-line-interface#--report-unused-disable-directives). Inline ESLint config within `@example` JavaScript is allowed (or within `@default`, etc.), though the disabling of ESLint directives which are not needed by the resolved rules will be reported as with the ESLint `--report-unused-disable-directives` command. ## Options for Determining ESLint Rule Applicability (allowInlineConfig, noDefaultExampleRules, matchingFileName, configFile, checkEslintrc, and baseConfig) The following options determine which individual ESLint rules will be applied to the JavaScript found within the `@example` tags (as determined to be applicable by the above regex options) or for the other tags checked by `checkDefaults`, `checkParams`, or `checkProperties` options. They are ordered by decreasing precedence: * `allowInlineConfig` - If not set to `false`, will allow inline config within the `@example` to override other config. Defaults to `true`. * `noDefaultExampleRules` - Setting to `true` will disable the default rules which are expected to be troublesome for most documentation use. See the section below for the specific default rules. * `configFile` - A config file. Corresponds to ESLint's [`-c`](https://eslint.org/docs/user-guide/command-line-interface#-c---config). * `matchingFileName` - Option for a file name (even non-existent) to trigger specific rules defined in one's config; usable with ESLint `.eslintrc.*` `overrides` -> `files` globs, to apply a desired subset of rules with `@example` (besides allowing for rules specific to examples, this option can be useful for enabling reuse of the same rules within `@example` as with JavaScript Markdown lintable by [other plugins](https://github.com/eslint/eslint-plugin-markdown), e.g., if one sets `matchingFileName` to `dummy.md/*.js` so that `@example` rules will follow rules for fenced JavaScript blocks within one's Markdown rules). (In ESLint 6's processor API and `eslint-plugin-markdown` < 2, one would instead use `dummy.md`.) For `@example` only. * `matchingFileNameDefaults` - As with `matchingFileName` but for use with `checkDefaults` and defaulting to `.jsdoc-defaults` as extension. * `matchingFileNameParams` - As with `matchingFileName` but for use with `checkParams` and defaulting to `.jsdoc-params` as extension. * `matchingFileNameProperties` As with `matchingFileName` but for use with `checkProperties` and defaulting to `.jsdoc-properties` as extension. * `checkEslintrc` - Defaults to `true` in adding rules based on an `.eslintrc.*` file. Setting to `false` corresponds to ESLint's [`--no-eslintrc`](https://eslint.org/docs/user-guide/command-line-interface#--no-eslintrc). If `matchingFileName` is set, this will automatically be `true` and will use the config corresponding to that file. If `matchingFileName` is not set and this value is set to `false`, the `.eslintrc.*` configs will not be checked. If `matchingFileName` is not set, and this is unset or set to `true`, the `.eslintrc.*` configs will be checked as though the file name were the same as the file containing the example, with any file extension changed to `".md/*.js"` (and if there is no file extension, `"dummy.md/*.js"` will be the result). This allows convenient sharing of similar rules with often also context-free Markdown as well as use of `overrides` as described under `matchingFileName`. Note that this option (whether set by `matchingFileName` or set manually to `true`) may come at somewhat of a performance penalty as the file's existence is checked by eslint. * `baseConfig` - Set to an object of rules with the same schema as `.eslintrc.*` for defaults. ### Rules Disabled by Default Unless noDefaultExampleRules is Set to true * `eol-last` (and `@stylistic/eol-last`) - Insisting that a newline "always" be at the end is less likely to be desired in sample code as with the code file convention. * `no-console` - This rule is unlikely to have inadvertent temporary debugging within examples. * `no-multiple-empty-lines` (and `@stylistic/no-multiple-empty-lines`) - This rule may be problematic for projects which use an initial newline just to start an example. Also, projects may wish to use extra lines within examples just for easier illustration purposes. * `no-undef` - Many variables in examples will be `undefined`. * `no-unused-vars` (and `@typescript-eslint/no-unused-vars`) - It is common to define variables for clarity without always using them within examples. * `padded-blocks` (and `@stylistic/padded-blocks`) - It can generally look nicer to pad a little even if one's code follows more stringency as far as block padding. * `jsdoc/require-file-overview` - Shouldn't check example for JSDoc blocks. * `jsdoc/require-jsdoc` - Wouldn't expect JSDoc blocks within JSDoc blocks. * `import/no-unresolved` - One wouldn't generally expect example paths to resolve relative to the current JavaScript file as one would with real code. * `import/unambiguous` - Snippets in examples are likely too short to always include full import/export info. * `node/no-missing-import` (and `n/no-missing-import`) - See `import/no-unresolved`. * `node/no-missing-require` (and `n/no-missing-require`) - See `import/no-unresolved`. For `checkDefaults`, `checkParams`, and `checkProperties`, the following expression-oriented rules will be used by default as well: * `quotes` (and `@stylistic/quotes`) - Will insist on "double". * `semi` (and `@stylistic/semi`) - Will insist on "never". * `strict` - Disabled. * `no-empty-function` - Disabled. * `no-new` - Disabled. * `no-unused-expressions` (and `@typescript-eslint/no-unused-expressions`) - Disabled. * `chai-friendly/no-unused-expressions` - Disabled. ### Options for checking other than @example (checkDefaults, checkParams, or checkProperties) * `checkDefaults` - Whether to check the values of `@default`/`@defaultvalue` tags * `checkParams` - Whether to check `@param`/`@arg`/`@argument` default values * `checkProperties` - Whether to check `@property`/`@prop` default values ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`example`| |Recommended|false| |Options|`allowInlineConfig`, `baseConfig`, `captionRequired`, `checkDefaults`, `checkEslintrc`, `checkParams`, `checkProperties`, `configFile`, `exampleCodeRegex`, `matchingFileName`, `matchingFileNameDefaults`, `matchingFileNameParams`, `matchingFileNameProperties`, `noDefaultExampleRules`, `paddedIndent`, `rejectExampleCodeRegex`, `reportUnusedDisableDirectives`| ## Failing examples The following patterns are considered problems: ````ts /** * @example alert('hello') */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-alert":2,"semi":["error","always"]}},"checkEslintrc":false}] // Message: @example error (no-alert): Unexpected alert. /** * @example alert('hello') */ class quux { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-alert":2,"semi":["error","always"]}},"checkEslintrc":false}] // Message: @example error (no-alert): Unexpected alert. /** * @example ```js alert('hello'); ``` */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```js([\\s\\S]*)```"}] // Message: @example error (semi): Extra semicolon. /** * @example * * ```js alert('hello'); ``` */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```js ([\\s\\S]*)```"}] // Message: @example error (semi): Extra semicolon. /** * @example * ```js alert('hello'); ``` */ var quux = { }; // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```js ([\\s\\S]*)```"}] // Message: @example error (semi): Extra semicolon. /** * @example ``` * js alert('hello'); ``` */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```\njs ([\\s\\S]*)```"}] // Message: @example error (semi): Extra semicolon. /** * @example Not JavaScript */ function quux () { } /** * @example quux2(); */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"rejectExampleCodeRegex":"^\\s*<.*>\\s*$"}] // Message: @example error (semi): Extra semicolon. /** * @example * quux(); // does something useful */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-undef":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":true}] // Message: @example error (no-undef): 'quux' is not defined. /** * @example Valid usage * quux(); // does something useful * * @example * quux('random unwanted arg'); // results in an error */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"captionRequired":true,"checkEslintrc":false}] // Message: Caption is expected for examples. /** * @example quux(); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] // Message: @example error (indent): Expected indentation of 0 spaces but found 1. /** * @example test() // eslint-disable-line semi */ function quux () {} // "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false,"noDefaultExampleRules":true,"reportUnusedDisableDirectives":true}] // Message: @example error: Unused eslint-disable directive (no problems were reported from 'semi'). /** * @example test() // eslint-disable-line semi */ function quux () {} // "jsdoc/check-examples": ["error"|"warn", {"allowInlineConfig":false,"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"noDefaultExampleRules":true}] // Message: @example error (semi): Missing semicolon. /** * @example const j = 5; * quux2(); */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"matchingFileName":"../../jsdocUtils.js"}] // Message: @example warning (id-length): Identifier name 'j' is too short (< 2). /** * @example const k = 5; * quux2(); */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"configFile":".eslintrc.json","matchingFileName":"../../jsdocUtils.js"}] // Message: @example warning (id-length): Identifier name 'k' is too short (< 2). /** * @example const m = 5; * quux2(); */ function quux2 () { } // Message: @example warning (id-length): Identifier name 'm' is too short (< 2). /** * @example const i = 5; * quux2() */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"paddedIndent":2}] // Message: @example warning (id-length): Identifier name 'i' is too short (< 2). /** * @example * const i = 5; * quux2() */ function quux2 () { } // Message: @example warning (id-length): Identifier name 'i' is too short (< 2). /** * @example const idx = 5; * quux2() */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"matchingFileName":"dummy.js"}] // Message: @example error (semi): Missing semicolon. /** * @example const idx = 5; * * quux2() */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"matchingFileName":"dummy.js"}] // Message: @example error (semi): Missing semicolon. /** * @example const idx = 5; * * quux2() */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false,"matchingFileName":"dummy.js"}] // Message: @example error: Parsing error: The keyword 'const' is reserved /** * @example // begin alert('hello') // end */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["warn","always"]}},"checkEslintrc":false,"exampleCodeRegex":"// begin[\\s\\S]*// end","noDefaultExampleRules":true}] // Message: @example warning (semi): Missing semicolon. /** * @typedef {string} Foo * @example * 'foo' */ // "jsdoc/check-examples": ["error"|"warn", {"captionRequired":true,"checkEslintrc":false}] // Message: Caption is expected for examples. /** * @example * const list: number[] = [1, 2, 3] * quux(list); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parser":"@typescript-eslint/parser","parserOptions":{"ecmaVersion":6},"rules":{"semi":["error","always"]}},"checkEslintrc":false}] // Message: @example error (semi): Missing semicolon. /** * @example * const test = something.find((_) => { * return _ * }); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parserOptions":{"ecmaVersion":6},"rules":{"semi":["error","always"]}}}] // Message: @example error (semi): Missing semicolon. /** * @example Say `Hello!` to the user. * First, import the function: * * ```js * import popup from './popup' * const aConstInSameScope = 5; * ``` * * Then use it like this: * * ```js * const aConstInSameScope = 7; * popup('Hello!') * ``` * * Here is the result on macOS: * * ![Screenshot](path/to/screenshot.jpg) */ // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parserOptions":{"ecmaVersion":2015,"sourceType":"module"},"rules":{"semi":["error","always"]}},"checkEslintrc":false,"exampleCodeRegex":"/^```(?:js|javascript)\\n([\\s\\S]*?)```$/gm"}] // Message: @example error (semi): Missing semicolon. /** * @example // begin alert('hello') // end * And here is another example: // begin alert('there') // end */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["warn","always"]}},"checkEslintrc":false,"exampleCodeRegex":"/\\/\\/ begin[\\s\\S]*?// end/g","noDefaultExampleRules":true}] // Message: @example warning (semi): Missing semicolon. /** * @example * quux(); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] // Message: @example error (indent): Expected indentation of 0 spaces but found 2. /** * @default 'abc' */ const str = 'abc'; // "jsdoc/check-examples": ["error"|"warn", {"checkDefaults":true}] // Message: @default error (quotes): Strings must use doublequote. /** * @param {myType} [name='abc'] */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"checkParams":true}] // Message: @param error (quotes): Strings must use doublequote. /** * @property {myType} [name='abc'] */ const obj = {}; // "jsdoc/check-examples": ["error"|"warn", {"checkProperties":true}] // Message: @property error (quotes): Strings must use doublequote. /** * Test function. * * @example functionName (paramOne: string, paramTwo?: any, * paramThree?: any): boolean test() * * @param {string} paramOne Parameter description. * @param {any} [paramTwo] Parameter description. * @param {any} [paramThree] Parameter description. * @returns {boolean} Return description. */ const functionName = function (paramOne, paramTwo, paramThree) { return false; }; // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parserOptions":{"ecmaVersion":2015,"sourceType":"module"},"rules":{"semi":["error","always"]}},"captionRequired":true,"checkEslintrc":false}] // Message: @example error (semi): Missing semicolon. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @example ```js alert('hello'); ``` */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"exampleCodeRegex":"```js([\\s\\S]*)```"}] /** * @example ```js alert('hello'); ``` */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"exampleCodeRegex":"/```js([\\s\\S]*)```/"}] /** * @example * // arbitrary example content */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false}] /** * @example * quux(); // does something useful */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"no-undef":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] /** * @example quux(); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] /** * @example Valid usage * quux(); // does something useful * * @example Invalid usage * quux('random unwanted arg'); // results in an error */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"captionRequired":true,"checkEslintrc":false}] /** * @example test() // eslint-disable-line semi */ function quux () {} // "jsdoc/check-examples": ["error"|"warn", {"checkEslintrc":false,"noDefaultExampleRules":true,"reportUnusedDisableDirectives":false}] /** * @example test() // eslint-disable-line semi */ function quux () {} // "jsdoc/check-examples": ["error"|"warn", {"allowInlineConfig":true,"baseConfig":{"rules":{"semi":["error","always"]}},"checkEslintrc":false,"noDefaultExampleRules":true}] /** * @example ```js alert('hello') ``` */ var quux = { }; // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"semi":["error","never"]}},"checkEslintrc":false,"exampleCodeRegex":"```js([\\s\\S]*)```"}] /** * @example * foo(function (err) { * throw err; * }); */ function quux () {} // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] /** * @example * const list: number[] = [1, 2, 3]; * quux(list); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parser":"@typescript-eslint/parser","parserOptions":{"ecmaVersion":6},"rules":{"semi":["error","always"]}},"checkEslintrc":false}] /** * @example const ident = 5; * quux2(); * bar(); */ function quux2 () { } // "jsdoc/check-examples": ["error"|"warn", {"paddedIndent":2}] /** * @example * function quux() { * bar(); * } */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"rules":{"indent":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] // Comment a(); export default {}; /** * */ function f () { } /** * Does quux * @example * // Do it! * quux(); */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"plugins":["jsdoc"],"rules":{"jsdoc/require-file-overview":["error"]}},"checkEslintrc":false,"noDefaultExampleRules":false}] /** * @default "abc" */ const str = 'abc'; // "jsdoc/check-examples": ["error"|"warn", {"checkDefaults":true}] /** * @default */ const str = 'abc'; // "jsdoc/check-examples": ["error"|"warn", {"checkDefaults":true}] /** * @param {myType} [name="abc"] */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"checkParams":true}] /** * @param {myType} name */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"checkParams":true}] /** * @property {myType} [name="abc"] */ const obj = {}; // "jsdoc/check-examples": ["error"|"warn", {"checkProperties":true}] /** * @property {myType} [name] */ const obj = {}; // "jsdoc/check-examples": ["error"|"warn", {"checkProperties":true}] /** * @default 'abc' */ const str = 'abc'; // "jsdoc/check-examples": ["error"|"warn", {"checkDefaults":false,"matchingFileNameDefaults":"dummy.js"}] /** * @param {myType} [name='abc'] */ function quux () { } // "jsdoc/check-examples": ["error"|"warn", {"checkParams":false,"matchingFileNameParams":"dummy.js"}] /** * @property {myType} [name='abc'] */ const obj = {}; // "jsdoc/check-examples": ["error"|"warn", {"checkProperties":false,"matchingFileNameProperties":"dummy.js"}] /** * Test function. * * @example functionName (paramOne: string, paramTwo?: any, * paramThree?: any): boolean test(); * * @param {string} paramOne Parameter description. * @param {any} [paramTwo] Parameter description. * @param {any} [paramThree] Parameter description. * @returns {boolean} Return description. */ const functionName = function (paramOne, paramTwo, paramThree) { return false; }; // "jsdoc/check-examples": ["error"|"warn", {"baseConfig":{"parserOptions":{"ecmaVersion":2015,"sourceType":"module"},"rules":{"semi":["error","always"]}},"captionRequired":true,"checkEslintrc":false}] ```` --- # check-indentation * [Options](#user-content-check-indentation-options) * [`allowIndentedSections`](#user-content-check-indentation-options-allowindentedsections) * [`excludeTags`](#user-content-check-indentation-options-excludetags) * [Context and settings](#user-content-check-indentation-context-and-settings) * [Failing examples](#user-content-check-indentation-failing-examples) * [Passing examples](#user-content-check-indentation-passing-examples) Reports invalid padding inside JSDoc blocks. Ignores parts enclosed in Markdown "code block"'s. For example, the following description is not reported: ```js /** * Some description: * ```html *
* test *
* ``` */ ``` ## Options A single options object has the following properties. ### allowIndentedSections Allows indentation of nested sections on subsequent lines (like bullet lists) ### excludeTags Array of tags (e.g., `['example', 'description']`) whose content will be "hidden" from the `check-indentation` rule. Defaults to `['example']`. By default, the whole JSDoc block will be checked for invalid padding. That would include `@example` blocks too, which can get in the way of adding full, readable examples of code without ending up with multiple linting issues. When disabled (by passing `excludeTags: []` option), the following code *will* report a padding issue: ```js /** * @example * anArray.filter((a) => { * return a.b; * }); */ ``` ## Context and settings ||| |---|---| |Context|everywhere| |Tags|N/A| |Recommended|false| |Options|`allowIndentedSections`, `excludeTags`| ## Failing examples The following patterns are considered problems: ````ts /** foo */ function quux () { } // Message: There must be no indentation. /** * foo * * @param bar * baz */ function quux () { } // Message: There must be no indentation. /** * Foo * bar */ class Moo {} // Message: There must be no indentation. /** * foo * * @example * anArray.filter((a) => { * return a.b; * }); */ function quux () { } // "jsdoc/check-indentation": ["error"|"warn", {"excludeTags":[]}] // Message: There must be no indentation. /** * foo * * @example * aaaa * @returns * eeee */ function quux () { } // Message: There must be no indentation. /** * foo * ```html *
* test *
* ``` * @returns * eeee */ function quux () { } // Message: There must be no indentation. /** * foo * ``` aaaa``` * @returns * eeee */ function quux () { } // Message: There must be no indentation. /** * @example * Here is a long * indented summary of this * example * * ```js * function hi () { * alert('Hello'); * } * ``` */ // "jsdoc/check-indentation": ["error"|"warn", {"excludeTags":[]}] // Message: There must be no indentation. /** * @example * Here is a long * summary of this * example * * // Code is not wrapped into fenced code block * function hi () { * alert('Hello'); * } */ // "jsdoc/check-indentation": ["error"|"warn", {"excludeTags":[]}] // Message: There must be no indentation. /** * @param {number} val Still disallowed */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] // Message: There must be no indentation. /** * Disallowed * Indentation */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] // Message: There must be no indentation. /** * Some text * that is indented * but is inconsistent */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] // Message: There must be no indentation. /** Indented on first line */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] // Message: There must be no indentation. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * foo * * @param bar * baz */ function quux () { } /*** foo */ function quux () { } /** * foo * * @example * anArray.filter((a) => { * return a.b; * }); */ function quux () { } /** * foo * * @example * anArray.filter((a) => { * return a.b; * }); * @returns * eeee */ function quux () { } // "jsdoc/check-indentation": ["error"|"warn", {"excludeTags":["example","returns"]}] /** * foo * ```html *
* test *
* ``` * @returns eeee */ function quux () { } /** * foo * ``` aaaa``` * @returns eeee */ function quux () { } /** * @example * Here is a long * summary of this * example * * ```js * function hi () { * alert('Hello'); * } * ``` */ // "jsdoc/check-indentation": ["error"|"warn", {"excludeTags":[]}] /** * @example * ``` * @MyDecorator({ * myOptions: 42 * }) * export class MyClass {} * ``` */ function MyDecorator(options: { myOptions: number }) { return (Base: Function) => {}; } // "jsdoc/check-indentation": ["error"|"warn", {"excludeTags":["example","MyDecorator"]}] /** * @example ``` * @MyDecorator({ * myOptions: 42 * }) * export class MyClass {} * ``` */ function MyDecorator(options: { myOptions: number }) { return (Base: Function) => {}; } /** * Foobar * * This method does the following things: * - foo... * this is the first step * - bar * this is the second step */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] /** * Allowed * Indentation */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] /** * @param {number} val Multi- * line */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] /** * - foo: * - bar */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] /** * Some text * that is indented * and continues at same level * and increases further */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] /** * Description * @param {string} foo Param * with continuation * at same indentation */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] /** * Description * * More content */ // "jsdoc/check-indentation": ["error"|"warn", {"allowIndentedSections":true}] ```` --- # check-line-alignment * [Fixer](#user-content-check-line-alignment-fixer) * [Options](#user-content-check-line-alignment-options) * [`customSpacings`](#user-content-check-line-alignment-options-customspacings) * [`disableWrapIndent`](#user-content-check-line-alignment-options-disablewrapindent) * [`preserveMainDescriptionPostDelimiter`](#user-content-check-line-alignment-options-preservemaindescriptionpostdelimiter) * [`tags`](#user-content-check-line-alignment-options-tags) * [`wrapIndent`](#user-content-check-line-alignment-options-wrapindent) * [Context and settings](#user-content-check-line-alignment-context-and-settings) * [Failing examples](#user-content-check-line-alignment-failing-examples) * [Passing examples](#user-content-check-line-alignment-passing-examples) Reports invalid alignment of JSDoc block lines. This is a [standard recommended to WordPress code](https://make.wordpress.org/core/handbook/best-practices/inline-documentation-standards/javascript/#aligning-comments), for example. ## Fixer Will either add alignment between the tag, type, name, and description across lines of the JSDoc block or remove it. ## Options The first option is a string with the following possible values: "always", "never", "any". If the string value is `"always"` then a problem is raised when the lines are not aligned. If it is `"never"` then a problem should be raised when there is more than one space between each line's parts. If it is `"any"`, no alignment is made. Defaults to `"never"`. Note that in addition to alignment, the "never" and "always" options will both ensure that at least one space is present after the asterisk delimiter. The next option is an object with the following properties. ### customSpacings A single options object has the following properties. An object with any of the following spacing keys set to an integer. If a spacing is not defined, it defaults to one. #### postDelimiter Affects spacing after the asterisk (e.g., `* @param`) #### postHyphen Affects spacing after any hyphens in the description (e.g., `* @param {someType} name - A description`) #### postName Affects spacing after the name (e.g., `* @param {someType} name `) #### postTag Affects spacing after the tag (e.g., `* @param `) #### postType Affects spacing after the type (e.g., `* @param {someType} `) ### disableWrapIndent Disables `wrapIndent`; existing wrap indentation is preserved without changes. ### preserveMainDescriptionPostDelimiter A boolean to determine whether to preserve the post-delimiter spacing of the main description. If `false` or unset, will be set to a single space. ### tags Use this to change the tags which are sought for alignment changes. Defaults to an array of `['param', 'arg', 'argument', 'property', 'prop', 'returns', 'return', 'template']`. ### wrapIndent The indent that will be applied for tag text after the first line. Default to the empty string (no indent). ## Context and settings ||| |---|---| |Context|everywhere| |Options|string ("always", "never", "any") followed by object with `customSpacings`, `disableWrapIndent`, `preserveMainDescriptionPostDelimiter`, `tags`, `wrapIndent`| |Tags|`param`, `property`, `returns` and others added by `tags`| |Aliases|`arg`, `argument`, `prop`, `return`| |Recommended|false| ## Failing examples The following patterns are considered problems: ````ts /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * With tabs. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @template {string} Arg Description. * @param {Arg} arg Description */ function hello(arg) {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ function fn( lorem, sit ) {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. const object = { /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ fn( lorem, sit ) {} } // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. class ClassName { /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ fn( lorem, sit ) {} } // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @arg {string} lorem Description. * @arg {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * @namespace * @property {object} defaults Description. * @property {int} defaults.lorem Description multi words. */ const config = { defaults: { lorem: 1 } } // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * My object. * * @typedef {Object} MyObject * * @property {string} lorem Description. * @property {int} sit Description multi words. */ // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * My object. * * @typedef {Object} MyObject * * @property {{a: number, b: string, c}} lorem Description. * @property {Object.} sit Description multi words. * @property {Object.} amet Description} weird {multi} {{words}}. * @property {Object.} dolor */ // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * My object. * * @typedef {Object} MyObject * * @property {{a: number, b: string, c}} lorem Description. * @property {Object.} sit Description multi words. * @property {Object.} amet Description} weird {multi} {{words}}. * @property {Object.} dolor */ // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"tags":["typedef","property"]}] // Message: Expected JSDoc block lines to be aligned. /** * My function. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * My function. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * My function. * * @param {string} lorem Description. * @param {int} sit */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * My function. * * @param {string} lorem Description. * @param {int} sit */ const fn = ( lorem, sit ) => {} // Message: Expected JSDoc block lines to not be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi line without *. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * My function. * * @param {string} lorem Description. * @param {int} sit * * @return {string} Return description * with multi line, but don't touch. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"tags":["param"]}] // Message: Expected JSDoc block lines to be aligned. /** * Only return doc. * * @return {boolean} Return description. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @return {boolean} True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @return {boolean} True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @return True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * Creates OS based shortcuts for files, folders, and applications. * * @param options Options object for each OS. * @return True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @param {object} other Other. * @return True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"tags":["param","return"]}] // Message: Expected JSDoc block lines to not be aligned. /** * Returns the value stored in the process.env for a given * environment variable. * * @param {string} withPercents '%USERNAME%' * @param {string} withoutPercents 'USERNAME' * @return {string} 'bob' || '%USERNAME%' */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * Function description * description with post delimiter. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. * * @return {string} Return description. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"customSpacings":{"postDelimiter":2,"postTag":3,"postType":2}}] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. * * @return {string} Return description. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"customSpacings":{"postName":3}}] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"customSpacings":{"postDelimiter":2,"postTag":3,"postType":2}}] // Message: Expected JSDoc block lines to not be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"customSpacings":{"postName":3}}] // Message: Expected JSDoc block lines to not be aligned. /**\r * Function description.\r *\r * @param {string} lorem Description.\r * @param {int} sit Description multi words.\r * @param {string} sth Multi\r * line description.\r */\r const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi * line with asterisks. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never"] // Message: Expected JSDoc block lines to not be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"customSpacings":{"postHyphen":2}}] // Message: Expected JSDoc block lines to not be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"customSpacings":{"postHyphen":2}}] // Message: Expected JSDoc block lines to not be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"customSpacings":{"postHyphen":2}}] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"customSpacings":{"postHyphen":2}}] // Message: Expected JSDoc block lines to be aligned. /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"customSpacings":{"postHyphen":2}}] // Message: Expected JSDoc block lines to not be aligned. /** * @param {string} lorem Description * with multiple lines. */ function quux () { } // "jsdoc/check-line-alignment": ["error"|"warn", "any",{"wrapIndent":" "}] // Message: Expected wrap indent /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi * line with asterisks. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"wrapIndent":" "}] // Message: Expected JSDoc block lines to be aligned. /** * My function. * * @param {string} lorem Description. * @param {int} sit Description multiple * lines. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] // Message: Expected JSDoc block lines to not be aligned. /** * @property {boolean} tls_verify_client_certificate - Whether our API should * enable TLS client authentication */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] // Message: Expected wrap indent /** * @property {boolean} tls_verify_client_certificate - Whether our API should * enable TLS client authentication */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":""}] // Message: Expected wrap indent ```` ## Passing examples The following patterns are not considered problems: ````ts /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * With tabs. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @param {string} lorem - Description. * @param {int} sit - Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * @param {string} lorem Description. * @param {int} sit */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * @param {int} sit * @param {string} lorem Description. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * No params. */ const fn = () => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ function fn( lorem, sit ) {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] const object = { /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ fn( lorem, sit ) {}, } // "jsdoc/check-line-alignment": ["error"|"warn", "always"] class ClassName { /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ fn( lorem, sit ) {} } // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @arg {string} lorem Description. * @arg {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * @namespace * @property {object} defaults Description. * @property {int} defaults.lorem Description multi words. */ const config = { defaults: { lorem: 1 } } // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * My object. * * @typedef {Object} MyObject * * @property {string} lorem Description. * @property {int} sit Description multi words. */ // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * My object. * * @typedef {Object} MyObject * * @property {{a: number, b: string, c}} lorem Description. * @property {Object.} sit Description multi words. * @property {Object.} amet Description} weird {multi} {{words}}. * @property {Object.} dolor */ // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * My object. * * @typedef {Object} MyObject * * @property {{a: number, b: string, c}} lorem Description. * @property {Object.} sit Description multi words. * @property {Object.} amet Description} weird {multi} {{words}}. * @property {Object.} dolor */ // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"tags":["typedef","property"]}] /** * My object. * * @template T * @template W,X,Y,Z * @template {string} K - K must be a string or string literal * @template {{ serious(): string }} Seriousalizable - must have a serious method * * @param {{a: number, b: string, c}} lorem Description. */ // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"tags":["template","param"]}] /** @param {number} lorem */ const fn = ( lorem ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @return {boolean} True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @return {boolean} */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Only return doc. * * @return {boolean} Return description. */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Not validating without option. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @return {boolean} True = success, false = failed to create the icon */ function quux (options) {} /** * Creates OS based shortcuts for files, folders, and applications. * * @param {object} options Options object for each OS. * @param {object} other Other. * @return True = success, false = failed to create the icon */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"tags":["param"]}] /** * @param parameter Description. */ function func(parameter){ } /** * Function description * description with post delimiter. * * @param {string} lorem Description. * @param {int} sit Description multi words. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"preserveMainDescriptionPostDelimiter":true}] /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. * * @return {string} Return description. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"customSpacings":{"postDelimiter":2,"postTag":3,"postType":2}}] /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi words. * * @return {string} Return description. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"customSpacings":{"postDelimiter":2,"postTag":3,"postType":2}}] /** * @param {{ * ids: number[] * }} params */ const fn = ({ids}) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /**\r * Function description.\r *\r * @param {string} lorem Description.\r * @param {int} sit Description multi words.\r * @param {string} sth Multi\r * line description.\r */\r const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @param lorem Description. * @param sit Description multi words. */ const fn = ( lorem, sit ) => {}; /** * Function description. * * @return Return description. */ const fn2 = () => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @param lorem Description. * @param sit Description multi words. * @return Return description. */ const fn = ( lorem, sit ) => {}; /** * Function description. * * @param lorem Description. * @param sit Description multi words. * @returns Return description. */ const fn2 = ( lorem, sit ) => {}; /** * Function description. * * @param a Description. * @param b Description multi words. * @returns Return description. */ const fn3 = ( a, b ) => {}; // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @argument lorem Description. * @return Return description. */ const fn = ( lorem ) => {}; /** * Function description. * * @argument lorem Description. * @returns Return description. */ const fn2 = ( lorem ) => {}; // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @arg a Description. * @returns Return description. */ const fn = ( a ) => {}; // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @arg lorem Description. * @param sit Return description. */ const fn = ( lorem, sit ) => {}; // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * Function description. * * @arg a Description. * @argument b Second description. * @returns Return description. */ const fn = ( a, b ) => {}; // "jsdoc/check-line-alignment": ["error"|"warn", "always"] /** * @param {string} lorem Description * with multiple lines. */ function quux () { } // "jsdoc/check-line-alignment": ["error"|"warn", "any",{"wrapIndent":" "}] /** * @param {string} lorem Description * with multiple lines. */ function quux () { } // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi * line with asterisks. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"wrapIndent":" "}] /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description multi * line with * asterisks. */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"wrapIndent":" "}] /** * @param { * string | number * } lorem Description * with multiple lines. */ function quux () { } // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * @param {string|string[]|TemplateResult|TemplateResult[]} event.detail.description - * Notification description */ function quux () {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * Returns cached value of negative scale of the world transform. * * @returns {number} -1 if world transform has negative scale, 1 otherwise. */ // "jsdoc/check-line-alignment": ["error"|"warn", "never"] /** * @param {string} lorem Description * with multiple lines preserving existing indentation when wrapIndent is disabled. */ function quux () { } // "jsdoc/check-line-alignment": ["error"|"warn", "any",{"disableWrapIndent":true}] /** * Function description with disableWrapIndent true, but wrapIndent defined. * Preserves existing indentation regardless of wrapIndent value. * * @param {string} lorem Description * with multiple lines. */ const fn = ( lorem ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "any",{"disableWrapIndent":true,"wrapIndent":" "}] /** * @return {Promise} A promise. * - On success, resolves. * - On error, rejects with details: * - When aborted, textStatus is "abort". * - On timeout, textStatus is "timeout". */ function test() {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * @param {string} lorem Description with list: * - First item * - Second item * - Nested item * - Another nested item */ function test() {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * @return {Promise} A promise. * 1. First step * 2. Second step with continuation * on another line * 3. Third step */ function test() {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * @param {Object} options Configuration options. * * First option * * Second option with details: * * Nested detail * * Another detail */ function test() {} // "jsdoc/check-line-alignment": ["error"|"warn", "never",{"wrapIndent":" "}] /** * @param {string} param Description with list: * - Item 1 * - Nested item */ function test(param) {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"wrapIndent":" "}] /** * Function description. * * @param {string} lorem Description. * @param {int} sit Description with list: * - First item * - Second item * - Nested item */ const fn = ( lorem, sit ) => {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"wrapIndent":" "}] /** * @return {Promise} A promise. * - On success, resolves. * - On error, rejects with details: * - When aborted, status is "abort". * - On timeout, status is "timeout". */ function test() {} // "jsdoc/check-line-alignment": ["error"|"warn", "always",{"wrapIndent":" "}] ```` --- # check-param-names * [Fixer](#user-content-check-param-names-fixer) * [Destructuring](#user-content-check-param-names-destructuring) * [Options](#user-content-check-param-names-options) * [`allowExtraTrailingParamDocs`](#user-content-check-param-names-options-allowextratrailingparamdocs) * [`checkDestructured`](#user-content-check-param-names-options-checkdestructured) * [`checkRestProperty`](#user-content-check-param-names-options-checkrestproperty) * [`checkTypesPattern`](#user-content-check-param-names-options-checktypespattern) * [`disableExtraPropertyReporting`](#user-content-check-param-names-options-disableextrapropertyreporting) * [`disableMissingParamChecks`](#user-content-check-param-names-options-disablemissingparamchecks) * [`enableFixer`](#user-content-check-param-names-options-enablefixer) * [`useDefaultObjectProperties`](#user-content-check-param-names-options-usedefaultobjectproperties) * [Context and settings](#user-content-check-param-names-context-and-settings) * [Failing examples](#user-content-check-param-names-failing-examples) * [Passing examples](#user-content-check-param-names-passing-examples) Ensures that parameter names in JSDoc are matched by corresponding items in the function declaration. ## Fixer Auto-removes `@param` duplicates (based on identical names). Note that this option will remove duplicates of the same name even if the definitions do not match in other ways (e.g., the second param will be removed even if it has a different type or description). ## Destructuring Note that by default the rule will not report parameters present on the docs but non-existing on the function signature when an object rest property is part of that function signature since the seemingly non-existing properties might actually be a part of the object rest property. ```js /** * @param options * @param options.foo */ function quux ({foo, ...extra}) {} ``` To require that `extra` be documented--and that any extraneous properties get reported--e.g., if there had been a `@param options.bar` above--you can use the `checkRestProperty` option which insists that the rest property be documented (and that there be no other implicit properties). Note, however, that JSDoc [does not appear](https://github.com/jsdoc/jsdoc/issues/1773) to currently support syntax or output to distinguish rest properties from other properties, so in looking at the docs alone without looking at the function signature, the disadvantage of enabling this option is that it may appear that there is an actual property named `extra`. ## Options A single options object has the following properties. ### allowExtraTrailingParamDocs If set to `true`, this option will allow extra `@param` definitions (e.g., representing future expected or virtual params) to be present without needing their presence within the function signature. Other inconsistencies between `@param`'s and present function parameters will still be reported. ### checkDestructured Whether to check destructured properties. Defaults to `true`. ### checkRestProperty If set to `true`, will require that rest properties are documented and that any extraneous properties (which may have been within the rest property) are documented. Defaults to `false`. ### checkTypesPattern Defines a regular expression pattern to indicate which types should be checked for destructured content (and that those not matched should not be checked). When one specifies a type, unless it is of a generic type, like `object` or `array`, it may be considered unnecessary to have that object's destructured components required, especially where generated docs will link back to the specified type. For example: ```js /** * @param {SVGRect} bbox - a SVGRect */ export const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; ``` By default `checkTypesPattern` is set to `/^(?:[oO]bject|[aA]rray|PlainObject|Generic(?:Object|Array))$/v`, meaning that destructuring will be required only if the type of the `@param` (the text between curly brackets) is a match for "Object" or "Array" (with or without initial caps), "PlainObject", or "GenericObject", "GenericArray" (or if no type is present). So in the above example, the lack of a match will mean that no complaint will be given about the undocumented destructured parameters. Note that the `/` delimiters are optional, but necessary to add flags. Defaults to using (only) the `v` flag, so to add your own flags, encapsulate your expression as a string, but like a literal, e.g., `/^object$/vi`. You could set this regular expression to a more expansive list, or you could restrict it such that even types matching those strings would not need destructuring. ### disableExtraPropertyReporting Whether to check for extra destructured properties. Defaults to `false`. Change to `true` if you want to be able to document properties which are not actually destructured. Keep as `false` if you expect properties to be documented in their own types. Note that extra properties will always be reported if another item at the same level is destructured as destructuring will prevent other access and this option is only intended to permit documenting extra properties that are available and actually used in the function. ### disableMissingParamChecks Whether to avoid checks for missing `@param` definitions. Defaults to `false`. Change to `true` if you want to be able to omit properties. ### enableFixer Set to `true` to auto-remove `@param` duplicates (based on identical names). Note that this option will remove duplicates of the same name even if the definitions do not match in other ways (e.g., the second param will be removed even if it has a different type or description). ### useDefaultObjectProperties Set to `true` if you wish to avoid reporting of child property documentation where instead of destructuring, a whole plain object is supplied as default value but you wish its keys to be considered as signalling that the properties are present and can therefore be documented. Defaults to `false`. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`| |Options|`allowExtraTrailingParamDocs`, `checkDestructured`, `checkRestProperty`, `checkTypesPattern`, `disableExtraPropertyReporting`, `disableMissingParamChecks`, `enableFixer`, `useDefaultObjectProperties`| |Tags|`param`| |Aliases|`arg`, `argument`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @param Foo */ function quux (foo = 'FOO') { } // Message: Expected @param names to be "foo". Got "Foo". /** * @arg Foo */ function quux (foo = 'FOO') { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} // Message: Expected @arg names to be "foo". Got "Foo". /** * @param Foo */ function quux (foo) { } // Message: Expected @param names to be "foo". Got "Foo". /** * @param Foo.Bar */ function quux (foo) { } // Message: @param path declaration ("Foo.Bar") appears before any real parameter. /** * @param foo * @param Foo.Bar */ function quux (foo) { } // Message: @param path declaration ("Foo.Bar") root node name ("Foo") does not match previous real parameter name ("foo"). /** * Assign the project to a list of employees. * @param {string} employees[].name - The name of an employee. * @param {string} employees[].department - The employee's department. */ function assign (employees) { }; // Message: @param path declaration ("employees[].name") appears before any real parameter. /** * Assign the project to a list of employees. * @param {string} employees[].name - The name of an employee. * @param {string} employees[].name - The employee's department. */ function assign (employees) { }; // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "employees[].name" /** * @param foo * @param foo.bar * @param bar */ function quux (bar, foo) { } // Message: Expected @param names to be "bar, foo". Got "foo, bar". /** * @param foo * @param bar */ function quux (foo) { } // Message: @param "bar" does not match an existing function parameter. /** * @param foo * @param foo */ function quux (foo) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "foo" class bar { /** * @param foo * @param foo */ quux (foo) { } } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "foo" /** * @param foo * @param foo */ function quux (foo, bar) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "foo" /** * @param foo * @param foo */ function quux (foo, foo) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "foo" /** * @param cfg * @param cfg.foo * @param cfg.foo */ function quux ({foo}) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "cfg.foo" /** * @param cfg * @param cfg.foo * @param cfg.foo */ function quux ({foo}) { } // Message: Duplicate @param "cfg.foo" /** * @param cfg * @param cfg.foo */ function quux ({foo, bar}) { } // Message: Missing @param "cfg.bar" /** * @param cfg * @param cfg.foo * @param [cfg.foo] * @param baz */ function quux ({foo}, baz) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "cfg.foo" /** * @param cfg * @param cfg.foo * @param [cfg.foo="with a default"] * @param baz */ function quux ({foo, bar}, baz) { } // Message: Missing @param "cfg.bar" /** * @param cfg * @param cfg.foo * @param [cfg.foo="with a default"] * @param baz */ function quux ({foo}, baz) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "cfg.foo" /** * @param cfg * @param [cfg.foo="with a default"] * @param baz */ function quux ({foo, bar}, baz) { } // Message: Missing @param "cfg.bar" /** * @param args */ function quux ({a, b}) { } // Message: Missing @param "args.a" /** * @param args */ function quux ({a, b} = {}) { } // Message: Missing @param "args.a" export class SomeClass { /** * @param prop */ constructor(private property: string) {} } // Message: Expected @param names to be "property". Got "prop". export class SomeClass { /** * @param prop * @param prop.foo */ constructor(prop: { foo: string, bar: string }) {} } // Message: Missing @param "prop.bar" export class SomeClass { /** * @param prop * @param prop.foo * @param prop.bar */ constructor(options: { foo: string, bar: string }) {} } // Message: @param "prop" does not match parameter name "options" export class SomeClass { /** * @param options * @param options.foo * @param options.bar */ constructor(options: { foo: string }) {} } // Message: @param "options.bar" does not exist on options /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":false}}} // Message: Unexpected tag `@param` /** * @param {Error} error Exit code * @param {number} [code = 1] Exit code */ function quux (error, cde = 1) { }; // Message: Expected @param names to be "error, cde". Got "error, code". /** * @param foo */ function quux ([a, b] = []) { } // Message: Missing @param "foo."0"" /** * @param options * @param options.foo */ function quux ({foo, ...extra}) { } // "jsdoc/check-param-names": ["error"|"warn", {"checkRestProperty":true}] // Message: Missing @param "options.extra" /** * @param cfg * @param cfg.foo * @param cfg.bar * @param cfg.extra */ function quux ({foo, ...extra}) { } // "jsdoc/check-param-names": ["error"|"warn", {"checkRestProperty":true}] // Message: @param "cfg.bar" does not exist on cfg /** * Converts an SVGRect into an object. * @param {SVGRect} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; // "jsdoc/check-param-names": ["error"|"warn", {"checkTypesPattern":"SVGRect"}] // Message: Missing @param "bbox.x" /** * Converts an SVGRect into an object. * @param {object} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; // Message: Missing @param "bbox.x" module.exports = class GraphQL { /** * @param fetchOptions * @param cacheKey */ fetch = ({ url, ...options }, cacheKey) => { } }; // "jsdoc/check-param-names": ["error"|"warn", {"checkRestProperty":true}] // Message: Missing @param "fetchOptions.url" /** * Testing * * @param options * @param options.one One * @param options.two Two * @param options.four Four */ function testingEslint(options: { one: string; two: string; three: string; }): string { return one + two + three; } // Message: Missing @param "options.three" /** * */ function quux() { } // Settings: {"jsdoc":{"structuredTags":{"see":{"name":false,"required":["name"]}}}} // Message: Cannot add "name" to `require` with the tag's `name` set to `false` /** * @param root * @param foo */ function quux ({foo, bar}, baz) { } // "jsdoc/check-param-names": ["error"|"warn", {"checkDestructured":false}] // Message: Expected @param names to be "root, baz". Got "root, foo". /** * Description. * @param {Object} options * @param {FooBar} foo */ function quux ({ foo: { bar } }) {} // Message: Missing @param "options.foo" /** * Description. * @param {Object} options * @param options.foo */ function quux ({ foo: { bar } }) {} // Message: Missing @param "options.foo.bar" /** * Description. * @param {object} options Options. * @param {object} options.foo A description. * @param {object} options.foo.bar */ function foo({ foo: { bar: { baz } }}) {} // Message: Missing @param "options.foo.bar.baz" /** * Returns a number. * @param {Object} props Props. * @param {Object} props.prop Prop. * @param {string} props.prop.a String. * @param {string} props.prop.b String. * @return {number} A number. */ export function testFn1 ({ prop = { a: 1, b: 2 } }) { } // "jsdoc/check-param-names": ["error"|"warn", {"useDefaultObjectProperties":false}] // Message: @param "props.prop.a" does not exist on props /** * @param {object} cfg * @param {string} cfg.foo * @param {string} cfg.bar * @param {object} cfg.extra */ function quux ({foo}) { } // Message: @param "cfg.bar" does not exist on cfg /** * @param {object} cfg * @param {string} cfg.foo * @param {string} cfg.bar * @param {object} cfg.extra */ function quux ({foo}) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableExtraPropertyReporting":true}] // Message: @param "cfg.bar" does not exist on cfg /** * @param {object} root * @param {object} root.cfg * @param {object} root.cfg.a * @param {string} root.cfg.a.foo * @param {string} root.cfg.a.bar * @param {object} root.cfg.a.extra */ function quux ({cfg: {a: {foo}}}) { } // Message: @param "root.cfg.a.bar" does not exist on root /** * @param {object} root * @param {object} root.cfg * @param {object} root.cfg.a * @param {string} root.cfg.a.foo * @param {string} root.cfg.a.bar * @param {object} root.cfg.a.extra */ function quux ({cfg: {a: {foo}}}) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableExtraPropertyReporting":true}] // Message: @param "root.cfg.a.bar" does not exist on root /** * @param {object} root * @param {object} root.cfg * @param {string} root.cfg.foo * @param {string} root.cfg.bar * @param {object} root.cfg.extra */ function quux ({cfg}) { } // Message: @param "root.cfg.foo" does not exist on root /** * @param foo * @param foo * on another line */ function quux (foo) { } // "jsdoc/check-param-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @param "foo" /** * @param barr This is the description of bar. Oops, we misspelled "bar" as "barr". */ declare function foo(bar: number) // Message: Expected @param names to be "bar". Got "barr". /** * @param foo * @param foo.bar */ function quux (bar, foo) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":false}] // Message: Expected @param names to be "bar, foo". Got "foo". /** * @param foo */ function quux (bar, baz) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":true}] // Message: Expected @param names to be "bar, baz". Got "foo". /** * @param bar * @param foo */ function quux (foo, bar) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":true}] // Message: Expected @param names to be "foo, bar". Got "bar, foo". /** * @param foo * @param bar */ function quux (foo) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":true}] // Message: @param "bar" does not match an existing function parameter. export interface B { /** * @param paramA Something something */ methodB(paramB: string): void }; // Message: Expected @param names to be "paramB". Got "paramA". interface A { /** * @param params Values for the placeholders */ getText(key: string, ...params: string[]): string } // Message: Expected @param names to be "key, ...params". Got "params". /** * @param arg Arg */ export function fn(...[type, arg]: FnArgs): void { // ... } // Message: Expected @param name to be "type". Got "arg". ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ function quux (foo) { } /** * @param foo */ function quux (foo) { } /** * @param foo * @param bar */ function quux (foo, bar) { } /** * @param foo * @param bar */ function quux (foo, bar, baz) { } /** * @param foo * @param foo.foo * @param bar */ function quux (foo, bar) { } /** * @param args */ function quux (...args) { } /** * @param foo * @param foo.a * @param foo.b */ function quux ({a, b}) { } /** * @param foo * @param foo.a * @param foo.b */ function quux ({"a": A, b}) { } /** * @param foo * @param foo."a" * @param foo.b */ function quux ({a: A, b}) { } /** * @param foo * @param foo."a-b" * @param foo.b */ function quux ({"a-b": A, b}) { } /** * @param foo * @param foo.bar * @param foo.baz * @param bar */ function quux (foo, bar) { } /** * Assign the project to a list of employees. * @param {object[]} employees - The employees who are responsible for the project. * @param {string} employees[].name - The name of an employee. * @param {string} employees[].department - The employee's department. */ function assign (employees) { }; export class SomeClass { /** * @param property */ constructor(private property: string) {} } export class SomeClass { /** * @param options * @param options.foo * @param options.bar */ constructor(options: { foo: string, bar: string }) {} } export class SomeClass { /** * @param options * @param options.foo * @param options.bar */ constructor({ foo, bar }: { foo: string, bar: string }) {} } export class SomeClass { /** * @param options * @param options.foo * @param options.bar */ constructor({ foo, bar }: { foo: string, bar: string }) {} } /** * @param {Error} error Exit code * @param {number} [code = 1] Exit code */ function quux (error, code = 1) { }; /** * @param foo * @param bar */ function quux (foo) { } // "jsdoc/check-param-names": ["error"|"warn", {"allowExtraTrailingParamDocs":true}] /** * @param cfg * @param cfg.foo * @param baz */ function quux ({foo}, baz) { } /** * @param cfg * @param cfg.foo * @param cfg2 */ function quux ({foo}, cfg2) { } /** * @param cfg * @param cfg.foo * @param baz * @param baz.cfg */ function quux ({foo}, {cfg}) { } /** * @param options * @param options.foo */ function quux ({foo, ...extra}) { } /** * @param foo * @param bar */ function quux (foo, bar, ...extra) { } /** * Converts an SVGRect into an object. * @param {SVGRect} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; /** * Converts an SVGRect into an object. * @param {object} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; // "jsdoc/check-param-names": ["error"|"warn", {"checkTypesPattern":"SVGRect"}] class CSS { /** * Set one or more CSS properties for the set of matched elements. * * @param {Object} propertyObject - An object of property-value pairs to set. */ setCssObject(propertyObject: {[key: string]: string | number}): void { } } /** * Logs a string. * * @param input - String to output. */ export default function (input: { [foo: string]: { a: string; b: string }; }): void { input; } export class Thing { foo: any; /** * @param {} C */ constructor(C: { new (): any }) { this.foo = new C(); } } /** * @param foo * @param root */ function quux (foo, {bar}) { } // "jsdoc/check-param-names": ["error"|"warn", {"checkDestructured":false}] class A { /** * Show a prompt. * @param hideButton true if button should be hidden, false otherwise * @param onHidden delegate to call when the prompt is hidden */ public async showPrompt(hideButton: boolean, onHidden: {(): void}): Promise { } } /** * Description. * @param {Object} options Options. * @param {FooBar} options.foo foo description. */ function quux ({ foo: { bar }}) {} /** * Description. * @param {FooBar} options * @param {Object} options.foo */ function quux ({ foo: { bar } }) {} // "jsdoc/check-param-names": ["error"|"warn", {"checkTypesPattern":"FooBar"}] /** * Description. * @param {Object} options * @param {FooBar} options.foo * @param {FooBar} options.baz */ function quux ({ foo: { bar }, baz: { cfg } }) {} /** * Item * * @param {object} props * @param {object} props.data - case data * @param {string} props.data.className - additional css class * @param props.val */ export default function Item({ data: { className, } = {}, val = 4 }) { } /** * @param obj * @param obj.data * @param obj.data."0" * @param obj.data."1" * @param obj.data."2" * @param obj.defaulting * @param obj.defaulting."0" * @param obj.defaulting."1" */ function Item({ data: [foo, bar, ...baz], defaulting: [quux, xyz] = [] }) { } /** * Returns a number. * @param {Object} props Props. * @param {Object} props.prop Prop. * @param {string} props.prop.a String. * @param {string} props.prop.b String. * @return {number} A number. */ export function testFn1 ({ prop = { a: 1, b: 2 } }) { } // "jsdoc/check-param-names": ["error"|"warn", {"useDefaultObjectProperties":true}] /** * @param {object} root * @param {object} root.cfg * @param {string} root.cfg.foo * @param {string} root.cfg.bar * @param {object} root.cfg.extra */ function quux ({cfg}) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableExtraPropertyReporting":true}] class A { /** * @param cfg * @param cfg.abc */ constructor({ [new.target.prop]: cX, abc }) { } } /** * @param root * @param root."0" Ignored * @param root."1" Our "b" */ const foo = ([, b]) => b; /** * @param arg1 This is the description for arg1. */ function foo(this: void, arg1: number): void; declare global { /** * @param arg1 This is the number for foo. */ function foo(this: void, arg1: number): void; } declare global { /** * @param r Range is 0-1. * @param g Range is 0-1. * @param b Range is 0-1. */ function Color( this: void, r: float, g: float, b: float, ): Color; } /** * @param this desc * @param bar number to return * @returns number returned back to caller */ function foo(this: T, bar: number): number { console.log(this.name); return bar; } /** * Documentation */ function quux (foo, bar) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":true}] /** * @param bar * @param bar.baz */ function quux (foo, bar) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":true}] /** * @param foo */ function quux (foo, bar) { } // "jsdoc/check-param-names": ["error"|"warn", {"disableMissingParamChecks":true}] /** * @param type Type * @param arg Arg */ export function fn(...[type, arg]: FnArgs): void { // ... } /** * @param c c * @param d d */ const inner = (c: number, d: string): void => { console.log(c); console.log(d); }; // Settings: {"jsdoc":{"contexts":["VariableDeclaration"]}} ```` --- # check-property-names * [Fixer](#user-content-check-property-names-fixer) * [Options](#user-content-check-property-names-options) * [`enableFixer`](#user-content-check-property-names-options-enablefixer) * [Context and settings](#user-content-check-property-names-context-and-settings) * [Failing examples](#user-content-check-property-names-failing-examples) * [Passing examples](#user-content-check-property-names-passing-examples) Ensures that property names in JSDoc are not duplicated on the same block and that nested properties have defined roots. ## Fixer Auto-removes `@property` duplicates (based on identical names). Note that this option will remove duplicates of the same name even if the definitions do not match in other ways (e.g., the second property will be removed even if it has a different type or description). ## Options A single options object has the following properties. ### enableFixer Set to `true` to auto-remove `@property` duplicates (based on identical names). Note that this option will remove duplicates of the same name even if the definitions do not match in other ways (e.g., the second property will be removed even if it has a different type or description). ## Context and settings ||| |---|---| |Context|Everywhere| |Options|`enableFixer`| |Tags|`property`| |Aliases|`prop`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @typedef (SomeType) SomeTypedef * @property Foo.Bar */ // Message: @property path declaration ("Foo.Bar") appears before any real property. /** * @typedef (SomeType) SomeTypedef * @property foo * @property Foo.Bar */ // Message: @property path declaration ("Foo.Bar") root node name ("Foo") does not match previous real property name ("foo"). /** * Assign the project to a list of employees. * @typedef (SomeType) SomeTypedef * @property {string} employees[].name - The name of an employee. * @property {string} employees[].department - The employee's department. */ // Message: @property path declaration ("employees[].name") appears before any real property. /** * Assign the project to a list of employees. * @typedef (SomeType) SomeTypedef * @property {string} employees[].name - The name of an employee. * @property {string} employees[].name - The employee's department. */ // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @property "employees[].name" /** * @typedef (SomeType) SomeTypedef * @property foo * @property foo */ // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @property "foo" /** * @typedef (SomeType) SomeTypedef * @property foo * @property foo */ // Message: Duplicate @property "foo" /** * @typedef (SomeType) SomeTypedef * @property cfg * @property cfg.foo * @property cfg.foo */ function quux ({foo, bar}) { } // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @property "cfg.foo" class Test { /** * @typedef (SomeType) SomeTypedef * @property cfg * @property cfg.foo * @property cfg.foo */ quux ({foo, bar}) { } } // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @property "cfg.foo" /** * @typedef (SomeType) SomeTypedef * @property cfg * @property cfg.foo * @property [cfg.foo] * @property baz */ function quux ({foo, bar}, baz) { } // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @property "cfg.foo" /** * @typedef (SomeType) SomeTypedef * @property cfg * @property cfg.foo * @property [cfg.foo="with a default"] * @property baz */ function quux ({foo, bar}, baz) { } // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @property "cfg.foo" /** * @typedef (SomeType) SomeTypedef * @prop foo * @prop foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":"prop"}}} // "jsdoc/check-property-names": ["error"|"warn", {"enableFixer":true}] // Message: Duplicate @prop "foo" /** * @typedef (SomeType) SomeTypedef * @property foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":false}}} // Message: Unexpected tag `@property` /** * @typedef {object} foo * @property {string} type * * @typedef {object} bar * @property {object} abc * @property {number} abc.def * @property {number} abc.def */ // Message: Duplicate @property "abc.def" /** * @typedef {object} foo * @property {string} type * * @typedef {object} bar * @property {object} abc * @property {number} abc */ // Message: Duplicate @property "abc" /** * @typedef {object} foo * @property {string} type * @property {string} type * * @typedef {object} bar * @property {object} abc */ // Message: Duplicate @property "type" ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ /** * @typedef (SomeType) SomeTypedef * @property foo */ /** * @typedef (SomeType) SomeTypedef * @prop foo */ /** * @typedef (SomeType) SomeTypedef * @property foo * @property bar */ /** * @typedef (SomeType) SomeTypedef * @property foo * @property foo.foo * @property bar */ /** * Assign the project to a list of employees. * @typedef (SomeType) SomeTypedef * @property {object[]} employees - The employees who are responsible for the project. * @property {string} employees[].name - The name of an employee. * @property {string} employees[].department - The employee's department. */ /** * @typedef (SomeType) SomeTypedef * @property {Error} error Exit code * @property {number} [code = 1] Exit code */ /** * @namespace (SomeType) SomeNamespace * @property {Error} error Exit code * @property {number} [code = 1] Exit code */ /** * @class * @property {Error} error Exit code * @property {number} [code = 1] Exit code */ function quux (code = 1) { this.error = new Error('oops'); this.code = code; } /** * @typedef (SomeType) SomeTypedef * @property foo * @property foo.bar * @property foo.baz * @property bar */ /** * @typedef {object} foo * @property {string} type * * @typedef {object} bar * @property {number} type */ /** * @typedef {object} foo * @property {string} type * * @typedef {object} bar * @property {number} anotherType */ ```` --- # check-syntax * [Context and settings](#user-content-check-syntax-context-and-settings) * [Failing examples](#user-content-check-syntax-failing-examples) * [Passing examples](#user-content-check-syntax-passing-examples) Reports against syntax not encouraged for the mode (e.g., Google Closure Compiler in "jsdoc" or "typescript" mode). Note that this rule will not check for types that are wholly invalid for a given mode, as that is covered by `valid-types`. Currently checks against: - Use of `=` in "jsdoc" or "typescript" mode Note that "jsdoc" actually allows Closure syntax, but with another option available for optional parameters (enclosing the name in brackets), the rule is enforced (except under "permissive" and "closure" modes). ## Context and settings ||| |---|---| |Context|everywhere| |Tags|N/A| |Recommended|false| ## Failing examples The following patterns are considered problems: ````ts /** * @param {string=} foo */ function quux (foo) { } // Message: Syntax should not be Google Closure Compiler style. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {string=} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"closure"}} /** * @param {string} [foo] */ function quux (foo) { } /** * */ function quux (foo) { } ```` --- # check-tag-names * [Fixer](#user-content-check-tag-names-fixer) * [Options](#user-content-check-tag-names-options) * [`definedTags`](#user-content-check-tag-names-options-definedtags) * [`enableFixer`](#user-content-check-tag-names-options-enablefixer) * [`inlineTags`](#user-content-check-tag-names-options-inlinetags) * [`jsxTags`](#user-content-check-tag-names-options-jsxtags) * [`typed`](#user-content-check-tag-names-options-typed) * [Context and settings](#user-content-check-tag-names-context-and-settings) * [Failing examples](#user-content-check-tag-names-failing-examples) * [Passing examples](#user-content-check-tag-names-passing-examples) Reports invalid block tag names. Valid [JSDoc 3 Block Tags](https://jsdoc.app/#block-tags) are: ``` abstract access alias async augments author borrows callback class classdesc constant constructs copyright default deprecated description enum event example exports external file fires function generator global hideconstructor ignore implements inheritdoc inner instance interface kind lends license listens member memberof memberof! mixes mixin module name namespace override package param private property protected public readonly requires returns see since static summary this throws todo tutorial type typedef variation version yields ``` `modifies` is also supported (see [source](https://github.com/jsdoc/jsdoc/blob/master/packages/jsdoc/lib/jsdoc/tag/dictionary/definitions.js#L594)) but is undocumented. The following synonyms are also recognized if you set them in `tagNamePreference` as a key (or replacement): ``` arg argument const constructor defaultvalue desc emits exception extends fileoverview func host method overview prop return var virtual yield ``` If you wish to allow in certain cases both a primary tag name and its alias(es), you can set a normally non-preferred tag name to itself to indicate that you want to allow both the default tag (in this case `@returns`) and a non-default (in this case `return`): ```js "tagNamePreference": { "return": "return", } ``` Because the tags indicated as replacements in `settings.jsdoc.tagNamePreference` will automatically be considered as valid, the above works. Likewise are the tag keys of `settings.jsdoc.structuredTags` automatically considered as valid (as their defining an expected structure for tags implies the tags may be used). For [TypeScript](https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html#supported-jsdoc) (or Closure), when `settings.jsdoc.mode` is set to `typescript` or `closure`, one may also use the following: ``` template ``` And for [Closure](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler), when `settings.jsdoc.mode` is set to `closure`, one may use the following (in addition to the JSDoc and TypeScript tags–though replacing `returns` with `return`): ``` define (synonym of `const` per jsdoc source) dict export externs final implicitCast (casing distinct from that recognized by jsdoc internally) inheritDoc (casing distinct from that recognized by jsdoc internally) noalias nocollapse nocompile noinline nosideeffects polymer polymerBehavior preserve record (synonym of `interface` per jsdoc source) struct suppress unrestricted ``` ...and these undocumented tags which are only in [source](https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/parsing/Annotation.java): ``` closurePrimitive customElement expose hidden idGenerator meaning mixinClass mixinFunction ngInject owner typeSummary wizaction ``` If you instead wish to reject a normally valid tag, e.g., `@todo`, one may set the tag to `false`: ```json { "rules": {}, "settings": { "jsdoc": { "tagNamePreference": { "todo": false } } } } ``` Also checks for unknown inline tags, with the following being permitted by default (see the `inlineTags` option): ``` link linkcode linkplain tutorial ``` ## Fixer Auto-removes types that are redundant with the [`typed` option](#user-content-typed). ## Options A single options object has the following properties. ### definedTags Use an array of `definedTags` strings to configure additional, allowed tags. The format is as follows: ```json { "definedTags": ["note", "record"] } ``` ### enableFixer Set to `false` to disable auto-removal of types that are redundant with the [`typed` option](#user-content-typed). ### inlineTags List of tags to allow inline. Defaults to array of `'link', 'linkcode', 'linkplain', 'tutorial'` ### jsxTags If this is set to `true`, all of the following tags used to control JSX output are allowed: ``` jsx jsxFrag jsxImportSource jsxRuntime ``` For more information, see the [babel documentation](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx). ### typed If this is set to `true`, additionally checks for tag names that are redundant when using a type checker such as TypeScript. These tags are always unnecessary when using TypeScript or similar: ``` augments callback class enum implements private property protected public readonly this type typedef ``` These tags are unnecessary except when inside a TypeScript `declare` context: ``` abstract access class constant constructs default enum export exports function global inherits instance interface member memberof memberOf method mixes mixin module name namespace override property requires static this ``` ## Context and settings ||| |---|---| |Context|everywhere| |Tags|N/A| |Recommended|true| |Options|`definedTags`, `enableFixer`, `inlineTags`, `jsxTags`, `typed`| |Settings|`tagNamePreference`, `mode`| ## Failing examples The following patterns are considered problems: ````ts /** @type {string} */let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@type' is redundant when using a type system. /** @type {string} */let a; // "jsdoc/check-tag-names": ["error"|"warn", {"enableFixer":false,"typed":true}] // Message: '@type' is redundant when using a type system. /** @type {string} */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@type' is redundant when using a type system. /** @type {string} */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@type' is redundant when using a type system. /** @type {string} */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@type' is redundant when using a type system. /** @type {string} - extra info */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@type' is redundant when using a type system. /** * Existing comment. * @type {string} */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@type' is redundant when using a type system. /** @abstract */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@abstract' is redundant outside of ambient (`declare`/`.d.ts`) contexts when using a type system. /** @abstract */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"enableFixer":false,"typed":true}] // Message: '@abstract' is redundant outside of ambient (`declare`/`.d.ts`) contexts when using a type system. const a = { /** @abstract */ b: true, }; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@abstract' is redundant outside of ambient (`declare`/`.d.ts`) contexts when using a type system. /** @template */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@template' without a name is redundant when using a type system. /** * Prior description. * * @template */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@template' without a name is redundant when using a type system. /** @typoo {string} */ let a; // Message: Invalid JSDoc tag name "typoo". /** @typoo {string} */ let a; // Settings: {"jsdoc":{"structuredTags":{"parameter":{"name":"namepath-referencing","required":["type","name"],"type":true}}}} // Message: Invalid JSDoc tag name "typoo". /** * @Param */ function quux () { } // Message: Invalid JSDoc tag name "Param". /** * @foo */ function quux () { } // Message: Invalid JSDoc tag name "foo". /** * @arg foo */ function quux (foo) { } // Message: Invalid JSDoc tag (preference). Replace "arg" JSDoc tag with "param". /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} // Message: Invalid JSDoc tag (preference). Replace "param" JSDoc tag with "arg". /** * @constructor foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"tag constructor":"cons"}}} // Message: Invalid JSDoc tag (preference). Replace "constructor" JSDoc tag with "cons". /** * @arg foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"arg":"somethingDifferent"}}} // Message: Invalid JSDoc tag (preference). Replace "arg" JSDoc tag with "somethingDifferent". /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"parameter"}}} // Message: Invalid JSDoc tag (preference). Replace "param" JSDoc tag with "parameter". /** * @bar foo */ function quux (foo) { } // Message: Invalid JSDoc tag name "bar". /** * @baz @bar foo */ function quux (foo) { } // "jsdoc/check-tag-names": ["error"|"warn", {"definedTags":["bar"]}] // Message: Invalid JSDoc tag name "baz". /** * @bar * @baz */ function quux (foo) { } // "jsdoc/check-tag-names": ["error"|"warn", {"definedTags":["bar"]}] // Message: Invalid JSDoc tag name "baz". /** * @todo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"todo":false}}} // Message: Blacklisted tag found (`@todo`) /** * @todo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"todo":{"message":"Please resolve to-dos or add to the tracker"}}}} // Message: Please resolve to-dos or add to the tracker /** * @todo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"todo":{"message":"Please use x-todo instead of todo","replacement":"x-todo"}}}} // Message: Please use x-todo instead of todo /** * @todo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"todo":55}}} // Message: Invalid `settings.jsdoc.tagNamePreference`. Values must be falsy, a string, or an object. /** * @property {object} a * @prop {boolean} b */ function quux () { } // Message: Invalid JSDoc tag (preference). Replace "prop" JSDoc tag with "property". /** * @abc foo * @abcd bar */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"abc":"abcd"}}} // "jsdoc/check-tag-names": ["error"|"warn", {"definedTags":["abcd"]}] // Message: Invalid JSDoc tag (preference). Replace "abc" JSDoc tag with "abcd". /** * @abc * @abcd */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"abc":"abcd"}}} // Message: Invalid JSDoc tag (preference). Replace "abc" JSDoc tag with "abcd". /** * @returns */ function quux (foo) {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: Invalid JSDoc tag (preference). Replace "returns" JSDoc tag with "return". /** * @modifies * @abstract * @access * @alias * @async * @augments * @author * @borrows * @callback * @class * @classdesc * @constant * @constructs * @copyright * @default * @deprecated * @description * @enum * @event * @example * @exports * @external * @file * @fires * @function * @generator * @global * @hideconstructor * @ignore * @implements * @inheritdoc * @inheritDoc * @inner * @instance * @interface * @kind * @lends * @license * @listens * @member * @memberof * @memberof! * @mixes * @mixin * @module * @name * @namespace * @override * @package * @param * @private * @property * @protected * @public * @readonly * @requires * @returns * @see * @since * @static * @summary * @this * @throws * @todo * @tutorial * @type * @typedef * @variation * @version * @yields */ function quux (foo) {} // Settings: {"jsdoc":{"mode":"badMode"}} // Message: Unrecognized value `badMode` for `settings.jsdoc.mode`. /** * @modifies * @abstract * @access * @alias * @async * @augments * @author * @borrows * @callback * @class * @classdesc * @constant * @constructs * @copyright * @default * @deprecated * @description * @enum * @event * @example * @exports * @external * @file * @fires * @function * @generator * @global * @hideconstructor * @ignore * @implements * @inheritdoc * @inheritDoc * @inner * @instance * @interface * @kind * @lends * @license * @listens * @member * @memberof * @memberof! * @mixes * @mixin * @module * @name * @namespace * @override * @package * @param * @private * @property * @protected * @public * @readonly * @requires * @returns * @see * @since * @static * @summary * @this * @throws * @todo * @tutorial * @type * @typedef * @variation * @version * @yields * @import * @internal * @overload * @satisfies * @template */ function quux (foo) {} // Settings: {"jsdoc":{"mode":"jsdoc"}} // Message: Invalid JSDoc tag name "import". /** * @externs */ function quux (foo) {} // Message: Invalid JSDoc tag name "externs". /** @jsx h */ /** @jsxFrag Fragment */ /** @jsxImportSource preact */ /** @jsxRuntime automatic */ // Message: Invalid JSDoc tag name "jsx". /** * @constructor */ function Test() { this.works = false; } // Settings: {"jsdoc":{"tagNamePreference":{"returns":"return"}}} // Message: Invalid JSDoc tag (preference). Replace "constructor" JSDoc tag with "class". /** @typedef {Object} MyObject * @property {string} id - my id */ // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@typedef' is redundant when using a type system. /** * @property {string} id - my id */ // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@property' is redundant when using a type system. /** @typedef {Object} MyObject */ // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@typedef' is redundant when using a type system. /** @typedef {Object} MyObject */ // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] // Message: '@typedef' is redundant when using a type system. /** * @todo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"todo":{"message":"Please don't use todo"}}}} // Message: Please don't use todo /** * An {@inline sth} tag in the description and {@another} with a {@link}. * @param {SomeType} name And an {@inlineTag} inside a tag description. * @param {AnotherType} anotherName And yet {@another} */ // Message: Invalid JSDoc inline tag name "inline" ```` ## Passing examples The following patterns are not considered problems: ````ts /** @default 0 */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** @default 0 */ declare let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** @abstract */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** @abstract */ declare let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** @abstract */ { declare let a; } // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] function test() { /** @abstract */ declare let a; } // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** @template name */ let a; // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** @param param - takes information */ function takesOne(param) {} // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** * @param foo */ function quux (foo) { } /** * @memberof! foo */ function quux (foo) { } /** * @arg foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} /** * @parameter foo */ function quux (foo) { } // Settings: {"jsdoc":{"structuredTags":{"parameter":{"name":"namepath-referencing","required":["type","name"],"type":true}}}} /** * @bar foo */ function quux (foo) { } // "jsdoc/check-tag-names": ["error"|"warn", {"definedTags":["bar"]}] /** * @baz @bar foo */ function quux (foo) { } // "jsdoc/check-tag-names": ["error"|"warn", {"definedTags":["baz","bar"]}] /** * @baz @bar foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"baz","returns":{"message":"Prefer `bar`","replacement":"bar"},"todo":false}}} /** * @returns */ function quux (foo) {} /** * @return */ function quux (foo) {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @modifies * @abstract * @access * @alias * @async * @augments * @author * @borrows * @callback * @class * @classdesc * @constant * @constructs * @copyright * @default * @deprecated * @description * @enum * @event * @example * @exports * @external * @file * @fires * @function * @generator * @global * @hideconstructor * @ignore * @implements * @inheritdoc * @inheritDoc * @inner * @instance * @interface * @kind * @lends * @license * @listens * @member * @memberof * @memberof! * @mixes * @mixin * @module * @name * @namespace * @override * @package * @param * @private * @property * @protected * @public * @readonly * @requires * @returns * @see * @since * @static * @summary * @this * @throws * @todo * @tutorial * @type * @typedef * @variation * @version * @yields */ function quux (foo) {} /** * @modifies * @abstract * @access * @alias * @async * @augments * @author * @borrows * @callback * @class * @classdesc * @constant * @constructs * @copyright * @default * @deprecated * @description * @enum * @event * @example * @exports * @external * @file * @fires * @function * @generator * @global * @hideconstructor * @ignore * @implements * @inheritdoc * @inheritDoc * @inner * @instance * @interface * @kind * @lends * @license * @listens * @member * @memberof * @memberof! * @mixes * @mixin * @module * @name * @namespace * @override * @package * @param * @private * @property * @protected * @public * @readonly * @requires * @returns * @see * @since * @static * @summary * @this * @throws * @todo * @tutorial * @type * @typedef * @variation * @version * @yields * @import * @internal * @overload * @satisfies * @template */ function quux (foo) {} // Settings: {"jsdoc":{"mode":"typescript"}} /** * @externs */ function quux (foo) {} // Settings: {"jsdoc":{"mode":"closure"}} /** * */ function quux (foo) { } /** * @todo */ function quux () { } /** * @extends Foo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"augments":{"message":"@extends is to be used over @augments.","replacement":"extends"}}}} /** * (Set tag name preference to itself to get aliases to * work along with main tag name.) * @augments Bar * @extends Foo */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"extends":"extends"}}} /** * Registers the `target` class as a transient dependency; each time the dependency is resolved a new instance will be created. * * @param target - The class / constructor function to register as transient. * * @example ```ts @transient() class Foo { } ``` * @param Time for a new tag */ export function transient(target?: T): T { // ... } /** @jsx h */ /** @jsxFrag Fragment */ /** @jsxImportSource preact */ /** @jsxRuntime automatic */ // "jsdoc/check-tag-names": ["error"|"warn", {"jsxTags":true}] /** * @internal */ // Settings: {"jsdoc":{"mode":"typescript"}} interface WebTwain { /** * Converts the images specified by the indices to base64 synchronously. * @function WebTwain#ConvertToBase64 * @returns {Base64Result} ConvertToBase64(): Base64Result; */ /** * Converts the images specified by the indices to base64 asynchronously. * @function WebTwain#ConvertToBase64 * @returns {boolean} */ ConvertToBase64(): boolean; } /** * @overload * @satisfies */ // Settings: {"jsdoc":{"mode":"typescript"}} /** * @module * A comment related to the module */ // "jsdoc/check-tag-names": ["error"|"warn", {"typed":true}] /** * An {@inline sth} tag in the description and {@another} with a {@link}. * @param {SomeType} name And an {@inlineTag} inside a tag description. * @param {AnotherType} anotherName And yet {@another} */ // "jsdoc/check-tag-names": ["error"|"warn", {"inlineTags":["inline","another","inlineTag","link"]}] /** * @typeParam T */ // Settings: {"jsdoc":{"tagNamePreference":{"template":"typeParam"}}} ```` --- # check-template-names Checks that any `@template` names are actually used in the connected `@typedef`, `@callback`, `@function` or type structure. Currently checks `ClassDeclaration`, `FunctionDeclaration`, `TSInterfaceDeclaration` or `TSTypeAliasDeclaration` such as: ```ts /** * @template D * @template V */ export type Pairs = [D, V | undefined]; ``` or ```js /** * @template D * @template V * @typedef {[D, V | undefined]} Pairs */ ``` ||| |---|---| |Context|everywhere| |Tags|`@template`| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @template D * @template V */ type Pairs = [X, Y | undefined]; // Message: @template D not in use /** * @template D * @template V */ export type Pairs = [X, Y | undefined]; // Message: @template D not in use /** * @template D * @template V * @typedef {[X, Y | undefined]} Pairs */ // Message: @template D not in use /** * @template D * @template V */ export type Pairs = [number, undefined]; // Message: @template D not in use /** * @template D * @template V * @typedef {[undefined]} Pairs */ // Settings: {"jsdoc":{"mode":"permissive"}} // Message: @template D not in use /** * @template D, U, V */ export type Extras = [D, U | undefined]; // Message: @template V not in use /** * @template D, U, V * @typedef {[D, U | undefined]} Extras */ // Message: @template V not in use /** * @template D * @template V * @typedef Pairs * @property {V} foo */ // Message: @template D not in use /** * @template D * @template V */ interface GenericIdentityFn { (arg: Type): Type; } // Message: @template D not in use /** * @template D * @template V */ export interface GenericIdentityFn { (arg: Type): Type; } // Message: @template D not in use /** * @template D * @template V */ export default interface GenericIdentityFn { (arg: Type): Type; } // Message: @template D not in use /** * @template D * @template V */ function identity(arg: Type): Type { return arg; } // Message: @template D not in use /** * @template D * @template V */ export function identity(arg: Type): Type { return arg; } // Message: @template D not in use /** * @template D * @template V */ export default function identity(arg: Type): Type { return arg; } // Message: @template D not in use /** * @template D * @template V */ class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: @template D not in use /** * @template D * @template V */ export class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: @template D not in use /** * @template D * @template V */ export default class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: @template D not in use /** * @template D * @template V */ export default class { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: @template D not in use /** * @template D * @template V * @callback * @returns {[X, Y | undefined]} */ // Message: @template D not in use /** * @template D * @template V * @function * @returns {[X, Y | undefined]} */ // Message: @template D not in use /** * @template D * @template V * @function * @param {[X, Y | undefined]} someParam */ // Message: @template D not in use /** * @template */ // Settings: {"jsdoc":{"tagNamePreference":{"template":false}}} // Message: Unexpected tag `@template` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @template D * @template V */ export type Pairs = [D, V | undefined]; /** * @template D * @template V * @typedef {[D, V | undefined]} Pairs */ /** * @template D, U, V */ export type Extras = [D, U, V | undefined]; /** * @template D, U, V * @typedef {[D, U, V | undefined]} Extras */ /** * @template X * @typedef {[D, U, V | undefined]} Extras * @typedef {[D, U, V | undefined]} Extras */ /** * @typedef Foo * @prop {string} bar */ /** * @template D * @template V * @typedef Pairs * @property {D} foo * @property {V} bar */ /** * @template Type */ interface GenericIdentityFn { (arg: Type): Type; } /** * @template Type */ export interface GenericIdentityFn { (arg: Type): Type; } /** * @template Type */ export default interface GenericIdentityFn { (arg: Type): Type; } /** * @template Type */ function identity(arg: Type): Type { return arg; } /** * @template Type */ export function identity(arg: Type): Type { return arg; } /** * @template Type */ export default function identity(arg: Type): Type { return arg; } /** * @template NumType */ class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @template NumType */ export class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @template NumType */ export default class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @template NumType */ export default class { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * Uses the provided callback to group the given array into the keys of a map. * Based on the array grouping proposal: https://github.com/tc39/proposal-array-grouping/ * * @template T * @param {T[]} array * @param {(value: T, index: number) => string} callbackFn * @returns {Map} */ export function mapGroupBy(array, callbackFn) { } /** * @template D * @template V * @callback * @returns {[D, V | undefined]} */ /** * @template D * @template V * @function * @returns {[D, V | undefined]} */ /** * @template D * @template V * @function * @param {[D, V | undefined]} someParam */ /** * @template {string} U */ export class User { /** * @type {U} */ name; } /** * @template {string} U */ export class User { /** * @param {U} name */ constructor(name) { this.name = name; } methodToIgnore() {} } /** * @template [ChannelDataType=undefined] * @param {string} messageType - A key used for sending and receiving messages. * @returns {MessageChannel} A channel that can create messages of its * own type. */ export function createMessageChannel(messageType) { // Note: It should also infer the type if the new channel is returned // directly rather than returned as a typed variable. /** @type {MessageChannel} */ const messageChannel = new MessageChannel(messageType); return messageChannel; } ```` --- # check-types * [Options](#user-content-check-types-options) * [`exemptTagContexts`](#user-content-check-types-options-exempttagcontexts) * [`noDefaults`](#user-content-check-types-options-nodefaults) * [`unifyParentAndChildTypeChecks`](#user-content-check-types-options-unifyparentandchildtypechecks) * [Why not capital case everything?](#user-content-check-types-why-not-capital-case-everything) * [Comparisons](#user-content-check-types-comparisons) * [Fixer](#user-content-check-types-fixer) * [Context and settings](#user-content-check-types-context-and-settings) * [Failing examples](#user-content-check-types-failing-examples) * [Passing examples](#user-content-check-types-passing-examples) Reports invalid types. By default, ensures that the casing of native types is the same as in this list: ``` undefined null boolean number bigint string symbol object (For TypeScript's sake, however, using `Object` when specifying child types on it like `Object`) Array Function Date RegExp ``` ## Options A single options object has the following properties. ### exemptTagContexts Avoids reporting when a bad type is found on a specified tag. A single options object has the following properties. ##### tag Set a key `tag` to the tag to exempt ##### types Set to `true` to indicate that any types on that tag will be allowed, or to an array of strings which will only allow specific bad types. If an array of strings is given, these must match the type exactly, e.g., if you only allow `"object"`, it will not allow `"object"`. Note that this is different from the behavior of `settings.jsdoc.preferredTypes`. This option is useful for normally restricting generic types like `object` with `preferredTypes`, but allowing `typedef` to indicate that its base type is `object`. ### noDefaults Insists that only the supplied option type map is to be used, and that the default preferences (such as "string" over "String") will not be enforced. The option's default is `false`. ### unifyParentAndChildTypeChecks @deprecated Use the `preferredTypes[preferredType]` setting of the same name instead. If this option is `true`, will currently override `unifyParentAndChildTypeChecks` on the `preferredTypes` setting. ## Why not capital case everything? Why are `boolean`, `number` and `string` exempt from starting with a capital letter? Let's take `string` as an example. In Javascript, everything is an object. The `String` object has prototypes for string functions such as `.toUpperCase()`. Fortunately we don't have to write `new String()` everywhere in our code. Javascript will automatically wrap string primitives into string Objects when we're applying a string function to a string primitive. This way the memory footprint is a tiny little bit smaller, and the [GC](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) has less work to do. So in a sense, there are two types of strings in Javascript: 1. `{string}` literals, also called primitives 2. `{String}` Objects. We use the primitives because it's easier to write and uses less memory. `{String}` and `{string}` are technically both valid, but they are not the same. ```js new String('lard') // String {0: "l", 1: "a", 2: "r", 3: "d", length: 4} 'lard' // "lard" new String('lard') === 'lard' // false ``` To make things more confusing, there are also object literals (like `{}`) and `Object` objects. But object literals are still static `Object`s and `Object` objects are instantiated objects. So an object primitive is still an `Object` object. However, `Object.create(null)` objects are not `instanceof Object`, however, so in the case of such a plain object we lower-case to indicate possible support for these objects. Also, nowadays, TypeScript also [discourages](https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#:~:text=%E2%9D%8C%20Don't%20ever%20use,used%20appropriately%20in%20JavaScript%20code.) use of `Object` as a lone type. However, one additional complexity is that TypeScript allows and actually [currently requires](https://github.com/microsoft/TypeScript/issues/20555) `Object` (with the initial upper-case) if used in the syntax `Object.` or `Object` is not useable in native TypeScript syntax, even if it is allowed within JSDoc. Basically, for primitives, we want to define the type as a primitive, because that's what we use in 99.9% of cases. For everything else, we use the type rather than the primitive. Otherwise it would all just be `{object}` (with the additional exception of the special case of `Object.<>` just mentioned). In short: It's not about consistency, rather about the 99.9% use case. (And some functions might not even support the objects if they are checking for identity.) ## Comparisons type name | `typeof` | check-types | testcase --|--|--|-- **Array** | object | **Array** | `([]) instanceof Array` -> `true` **Function** | function | **Function** | `(function f () {}) instanceof Function` -> `true` **Date** | object | **Date** | `(new Date()) instanceof Date` -> `true` **RegExp** | object | **RegExp** | `(new RegExp(/.+/)) instanceof RegExp` -> `true` Object | **object** | **object** | `({}) instanceof Object` -> `true` but `Object.create(null) instanceof Object` -> `false` Boolean | **boolean** | **boolean** | `(true) instanceof Boolean` -> **`false`** Number | **number** | **number** | `(41) instanceof Number` -> **`false`** String | **string** | **string** | `("test") instanceof String` -> **`false`** If you define your own tags and don't wish their bracketed portions checked for types, you can use `settings.jsdoc.structuredTags` with a tag `type` of `false`. If you set their `type` to an array, only those values will be permitted. ## Fixer Replaces native types with standard casing and replaces according to `preferredTypes` settings. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`augments`, `class`, `constant`, `enum`, `implements`, `member`, `module`, `namespace`, `param`, `property`, `returns`, `throws`, `type`, `typedef`, `yields`| |Aliases|`constructor`, `const`, `extends`, `var`, `arg`, `argument`, `prop`, `return`, `exception`, `yield`| |Closure-only|`package`, `private`, `protected`, `public`, `static`| |Recommended|true| |Options|`exemptTagContexts`, `noDefaults`, `unifyParentAndChildTypeChecks`| |Settings|`preferredTypes`, `mode`, `structuredTags`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {abc} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":100}}} // Message: Invalid `settings.jsdoc.preferredTypes`. Values must be falsy, a string, or an object. /** * @param {Number} foo */ function quux (foo) { } // Message: Invalid JSDoc @param "foo" type "Number"; prefer: "number". /** * @arg {Number} foo */ function quux (foo) { } // Message: Invalid JSDoc @arg "foo" type "Number"; prefer: "number". /** * @returns {Number} foo * @throws {Number} foo */ function quux () { } // Message: Invalid JSDoc @returns type "Number"; prefer: "number". /** * @param {(Number | string | Boolean)=} foo */ function quux (foo, bar, baz) { } // Message: Invalid JSDoc @param "foo" type "Number"; prefer: "number". /** * @param {Array.} foo */ function quux (foo, bar, baz) { } // Message: Invalid JSDoc @param "foo" type "Number"; prefer: "number". /** * @param {(Number | String)[]} foo */ function quux (foo, bar, baz) { } // Message: Invalid JSDoc @param "foo" type "Number"; prefer: "number". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":"Abc","string":"Str"}}} // Message: Invalid JSDoc @param "foo" type "abc"; prefer: "Abc". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":{"replacement":"Abc"},"string":"Str"}}} // Message: Invalid JSDoc @param "foo" type "abc"; prefer: "Abc". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":{"message":"Messed up JSDoc @{{tagName}}{{tagValue}} type \"abc\"; prefer: \"Abc\".","replacement":"Abc"},"string":"Str"}}} // Message: Messed up JSDoc @param "foo" type "abc"; prefer: "Abc". /** * @param {abc} foo * @param {cde} bar * @param {object} baz */ function qux(foo, bar, baz) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":{"message":"Messed up JSDoc @{{tagName}}{{tagValue}} type \"abc\"; prefer: \"Abc\".","replacement":"Abc"},"cde":{"message":"More messed up JSDoc @{{tagName}}{{tagValue}} type \"cde\"; prefer: \"Cde\".","replacement":"Cde"},"object":"Object"}}} // Message: Messed up JSDoc @param "foo" type "abc"; prefer: "Abc". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":{"message":"Messed up JSDoc @{{tagName}}{{tagValue}} type \"abc\".","replacement":false},"string":"Str"}}} // Message: Messed up JSDoc @param "foo" type "abc". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":{"message":"Messed up JSDoc @{{tagName}}{{tagValue}} type \"abc\"."},"string":"Str"}}} // Message: Messed up JSDoc @param "foo" type "abc". /** * @param {abc} foo * @param {Number} bar */ function qux(foo, bar) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":"Abc","string":"Str"}}} // "jsdoc/check-types": ["error"|"warn", {"noDefaults":true}] // Message: Invalid JSDoc @param "foo" type "abc"; prefer: "Abc". /** * @param {abc} foo * @param {Number} bar */ function qux(foo, bar) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":"Abc","string":"Str"}}} // Message: Invalid JSDoc @param "foo" type "abc"; prefer: "Abc". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":false,"string":"Str"}}} // Message: Invalid JSDoc @param "foo" type "abc". /** * @param {abc} foo */ function qux(foo) { } // Settings: {"jsdoc":{"preferredTypes":{"abc":false}}} // Message: Invalid JSDoc @param "foo" type "abc". /** * @param {*} baz */ function qux(baz) { } // Settings: {"jsdoc":{"preferredTypes":{"*":false,"abc":"Abc","string":"Str"}}} // Message: Invalid JSDoc @param "baz" type "*". /** * @param {*} baz */ function qux(baz) { } // Settings: {"jsdoc":{"preferredTypes":{"*":"aaa","abc":"Abc","string":"Str"}}} // Message: Invalid JSDoc @param "baz" type "*"; prefer: "aaa". /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"GenericArray"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "GenericArray". /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"GenericArray","Array.<>":"GenericArray"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "GenericArray". /** * @param {Array.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.<>":"GenericArray"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "GenericArray". /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array<>":"GenericArray"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "GenericArray". /** * @param {string[]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"SpecialTypeArray"}}} // Message: Invalid JSDoc @param "foo" type "[]"; prefer: "SpecialTypeArray". /** * @param {string[]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"SpecialTypeArray"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "[]"; prefer: "SpecialTypeArray". /** * @param {string[]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"SpecialTypeArray"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "SpecialTypeArray". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject","object.<>":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject","object<>":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object.<>":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object<>":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object.<>":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object<>":"GenericObject"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":false}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "object". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":false}}} // Message: Invalid JSDoc @param "foo" type "object". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "object"; prefer: "GenericObject". /** * * @param {string[][]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"Array."}}} // Message: Invalid JSDoc @param "foo" type "[]"; prefer: "Array.". /** * * @param {string[][]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"Array.<>"}}} // Message: Invalid JSDoc @param "foo" type "[]"; prefer: "Array.<>". /** * * @param {string[][]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"Array<>"}}} // Message: Invalid JSDoc @param "foo" type "[]"; prefer: "Array<>". /** * * @param {object.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object.":"Object"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object". /** * * @param {object.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object.":"Object<>"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object<>". /** * * @param {object>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object<>":"Object."}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object.". /** * * @param {Array.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.":"[]"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "[]". /** * * @param {Array.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.":"Array<>"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "Array<>". /** * * @param {Array.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.":"<>"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "<>". /** * * @param {Array.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.":"<>"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "<>". /** * * @param {Array.>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"MyArray.":"<>"}}} // Message: Invalid JSDoc @param "foo" type "MyArray"; prefer: "<>". /** * * @param {Array>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"<>":"Array."}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "Array.". /** * * @param {Array>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"Array."}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "Array.". /** * * @param {Array>} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"<>":"[]"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "[]". /** @typedef {String} foo */ // Message: Invalid JSDoc @typedef "foo" type "String"; prefer: "string". /** * @this {array} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: Invalid JSDoc @this type "array"; prefer: "Array". /** * @export {array} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: Invalid JSDoc @export type "array"; prefer: "Array". /** * @typedef {object} foo * @property {object} bar */ // Settings: {"jsdoc":{"preferredTypes":{"object":"Object"}}} // "jsdoc/check-types": ["error"|"warn", {"exemptTagContexts":[{"tag":"typedef","types":true}]}] // Message: Invalid JSDoc @property "bar" type "object"; prefer: "Object". /** @typedef {object} foo */ // Settings: {"jsdoc":{"preferredTypes":{"object":"Object"}}} // "jsdoc/check-types": ["error"|"warn", {"exemptTagContexts":[{"tag":"typedef","types":["array"]}]}] // Message: Invalid JSDoc @typedef "foo" type "object"; prefer: "Object". /** * @typedef {object} foo * @property {object} bar */ // Settings: {"jsdoc":{"preferredTypes":{"object":"Object"}}} // "jsdoc/check-types": ["error"|"warn", {"exemptTagContexts":[{"tag":"typedef","types":["object"]}]}] // Message: Invalid JSDoc @property "bar" type "object"; prefer: "Object". /** @typedef {object} foo */ // Settings: {"jsdoc":{"preferredTypes":{"object<>":"Object<>"}}} // "jsdoc/check-types": ["error"|"warn", {"exemptTagContexts":[{"tag":"typedef","types":["object"]}]}] // Message: Invalid JSDoc @typedef "foo" type "object"; prefer: "Object<>". /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.<>":"[]","Array<>":"[]"}}} // Message: Invalid JSDoc @param "foo" type "Array"; prefer: "[]". /** * @typedef {object} foo */ function a () {} /** * @typedef {Object} foo */ function b () {} // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"object":"Object"}}} // Message: Invalid JSDoc @typedef "foo" type "object"; prefer: "Object". /** * @aCustomTag {Number} foo */ // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":true}}}} // Message: Invalid JSDoc @aCustomTag "foo" type "Number"; prefer: "number". /** * @aCustomTag {Number} foo */ // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":["otherType","anotherType"]}}}} // Message: Invalid JSDoc @aCustomTag "foo" type "Number"; prefer: ["otherType","anotherType"]. /** * @param {Object[]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object"}}} // Message: Invalid JSDoc @param "foo" type "Object"; prefer: "object". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"object.<>":"Object"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":"Object<>","Object.<>":"Object<>","object<>":"Object<>"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object<>". /** * @param {Object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":"Object<>","Object.<>":"Object<>","object<>":"Object<>"}}} // Message: Invalid JSDoc @param "foo" type "Object"; prefer: "Object<>". /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":"Object<>","Object.<>":"Object<>","object<>":"Object<>"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object<>". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":"Object<>","Object.<>":"Object<>","object<>":"Object<>"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object<>". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript"}} // Message: Use object shorthand or index signatures instead of `object`, e.g., `{[key: string]: string}` /** * * @param {Object} param * @return {Object | String} */ function abc(param) { if (param.a) return {}; return 'abc'; } // Message: Invalid JSDoc @param "param" type "Object"; prefer: "object". /** * @param {object} root * @param {number} root.a * @param {object} b */ function a () {} // Settings: {"jsdoc":{"preferredTypes":{"object":{"skipRootChecking":true}}}} // Message: Invalid JSDoc @param "b" type "object". /** * @typedef {Object} foo */ function a () {} // Settings: {"jsdoc":{"preferredTypes":{"Object":{"replacement":"object","unifyParentAndChildTypeChecks":true}}}} // Message: Invalid JSDoc @typedef "foo" type "Object"; prefer: "object". /** * @typedef {Object} foo */ function a () {} // Settings: {"jsdoc":{"preferredTypes":{"Object":{"replacement":"object","unifyParentAndChildTypeChecks":true}}}} // Message: Invalid JSDoc @typedef "foo" type "Object"; prefer: "object". /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":{"replacement":"Object<>","unifyParentAndChildTypeChecks":true},"Object.<>":"Object<>","object<>":"Object<>"}}} // Message: Invalid JSDoc @param "foo" type "object"; prefer: "Object<>". ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {number} foo * @param {Bar} bar * @param {*} baz */ function quux (foo, bar, baz) { } /** * @arg {number} foo * @arg {Bar} bar * @arg {*} baz */ function quux (foo, bar, baz) { } /** * @param {(number | string | boolean)=} foo */ function quux (foo, bar, baz) { } /** * @param {typeof bar} foo */ function qux(foo) { } /** * @param {import('./foo').bar.baz} foo */ function qux(foo) { } /** * @param {(x: number, y: string) => string} foo */ function qux(foo) { } /** * @param {() => string} foo */ function qux(foo) { } /** * @returns {Number} foo * @throws {Number} foo */ function quux () { } // "jsdoc/check-types": ["error"|"warn", {"noDefaults":true}] /** * @param {Object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"Object"}}} /** * @param {Array} foo */ function quux (foo) { } /** * @param {Array.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"GenericArray"}}} /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"GenericArray"}}} /** * @param {string[]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array":"SpecialTypeArray","Array.<>":"SpecialTypeArray","Array<>":"SpecialTypeArray"}}} /** * @param {string[]} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.<>":"SpecialTypeArray","Array<>":"SpecialTypeArray"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"SpecialTypeArray"}}} /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"[]":"SpecialTypeArray"}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array.<>":"GenericArray"}}} /** * @param {Array} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"Array<>":"GenericArray"}}} /** * @param {object} foo */ function quux (foo) { } /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} /** * @param {object.} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object":"GenericObject"}}} /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object.<>":"GenericObject"}}} /** * @param {object} foo */ function quux (foo) { } // Settings: {"jsdoc":{"preferredTypes":{"object<>":"GenericObject"}}} /** * @param {Number<} Ignore the error as not a validating rule */ function quux (foo) { } /** @param {function(...)} callback The function to invoke. */ var subscribe = function(callback) {}; /** * @this {Array} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @export {Array} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** @type {new() => EntityBase} */ /** @typedef {object} foo */ // Settings: {"jsdoc":{"preferredTypes":{"object":"Object"}}} // "jsdoc/check-types": ["error"|"warn", {"exemptTagContexts":[{"tag":"typedef","types":true}]}] /** @typedef {object} foo */ // Settings: {"jsdoc":{"preferredTypes":{"object":"Object"}}} /** @typedef {object} foo */ // Settings: {"jsdoc":{"preferredTypes":{"object<>":"Object<>"}}} // "jsdoc/check-types": ["error"|"warn", {"exemptTagContexts":[{"tag":"typedef","types":["object"]}]}] /** * @typedef {object} foo */ /** * @typedef {Object} foo */ // Settings: {"jsdoc":{"preferredTypes":{"object":"Object","Object":"object"}}} /** * @typedef {object} foo */ function a () {} /** * @typedef {Object} foo */ function b () {} // Settings: {"jsdoc":{"preferredTypes":{"object":"Object","Object":"object"}}} /** * @typedef {object} foo */ function a () {} /** * @typedef {{[key: string]: number}} foo */ function b () {} // Settings: {"jsdoc":{"mode":"typescript"}} /** * @aCustomTag {Number} foo */ // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":false}}}} /** * @aCustomTag {otherType} foo */ // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":["otherType","anotherType"]}}}} /** * @aCustomTag {anotherType|otherType} foo */ // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":["otherType","anotherType"]}}}} /** * Bad types handled by `valid-types` instead. * @param {str(} foo */ function quux (foo) { } /** * @param {{[key: string]: number}} foo */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @typedef {object} foo */ function a () {} // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":"Object<>","object<>":"Object<>"}}} /** * @typedef {Object} foo */ function a () {} // Settings: {"jsdoc":{"mode":"typescript","preferredTypes":{"Object":"object","object.<>":"Object<>","object<>":"Object<>"}}} /** * Does something. * * @param {Object} spec - Foo. */ function foo(spec) { return spec; } foo() // Settings: {"jsdoc":{"mode":"jsdoc"}} /** * @param {object} root * @param {number} root.a */ function a () {} // Settings: {"jsdoc":{"preferredTypes":{"object":{"message":"Won't see this message","skipRootChecking":true}}}} /** * @returns {string | undefined} a string or undefined */ function quux () {} // Settings: {"jsdoc":{"preferredTypes":{"[]":{"message":"Do not use *[], use Array<*> instead","replacement":"Array"}}}} // "jsdoc/check-types": ["error"|"warn", {"unifyParentAndChildTypeChecks":true}] /** * @typedef {object} foo */ function a () {} // Settings: {"jsdoc":{"preferredTypes":{"Object":{"replacement":"object","unifyParentAndChildTypeChecks":true}}}} ```` --- # check-values * [Options](#user-content-check-values-options) * [`allowedAuthors`](#user-content-check-values-options-allowedauthors) * [`allowedLicenses`](#user-content-check-values-options-allowedlicenses) * [`licensePattern`](#user-content-check-values-options-licensepattern) * [`numericOnlyVariation`](#user-content-check-values-options-numericonlyvariation) * [Context and settings](#user-content-check-values-context-and-settings) * [Failing examples](#user-content-check-values-failing-examples) * [Passing examples](#user-content-check-values-passing-examples) This rule checks the values for a handful of tags: 1. `@version` - Checks that there is a present and valid [semver](https://semver.org/) version value. 2. `@since` - As with `@version` 3. `@license` - Checks that there is a present and valid SPDX identifier or is present within an `allowedLicenses` option. 4. `@author` - Checks that there is a value present, and if the option `allowedAuthors` is present, ensure that the author value is one of these array items. 5. `@variation` - If `numericOnlyVariation` is set, will checks that there is a value present, and that it is an integer (otherwise, jsdoc allows any value). 6. `@kind` - Insists that it be one of the allowed values: 'class', 'constant', 'event', 'external', 'file', 'function', 'member', 'mixin', 'module', 'namespace', 'typedef', 7. `@import` - For TypeScript `mode` only. Enforces valid ES import syntax. ## Options A single options object has the following properties. ### allowedAuthors An array of allowable author values. If absent, only non-whitespace will be checked for. ### allowedLicenses An array of allowable license values or `true` to allow any license text. If present as an array, will be used in place of [SPDX identifiers](https://spdx.org/licenses/). ### licensePattern A string to be converted into a `RegExp` (with `v` flag) and whose first parenthetical grouping, if present, will match the portion of the license description to check (if no grouping is present, then the whole portion matched will be used). Defaults to `/([^\n\r]*)/gv`, i.e., the SPDX expression is expected before any line breaks. Note that the `/` delimiters are optional, but necessary to add flags. Defaults to using the `v` flag, so to add your own flags, encapsulate your expression as a string, but like a literal, e.g., `/^mit$/vi`. ### numericOnlyVariation Whether to enable validation that `@variation` must be a number. Defaults to `false`. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`@version`, `@since`, `@kind`, `@license`, `@author`, `@variation`| |Recommended|true| |Options|`allowedAuthors`, `allowedLicenses`, `licensePattern`, `numericOnlyVariation`| |Settings|`tagNamePreference`| ## Failing examples The following patterns are considered problems: ````ts /** * @version */ function quux (foo) { } // Message: Missing JSDoc @version value. /** * @version 3.1 */ function quux (foo) { } // Message: Invalid JSDoc @version: "3.1". /** * @kind */ function quux (foo) { } // Message: Missing JSDoc @kind value. /** * @kind -3 */ function quux (foo) { } // Message: Invalid JSDoc @kind: "-3"; must be one of: class, constant, event, external, file, function, member, mixin, module, namespace, typedef. /** * @variation -3 */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"numericOnlyVariation":true}] // Message: Invalid JSDoc @variation: "-3". /** * @since */ function quux (foo) { } // Message: Missing JSDoc @since value. /** * @since 3.1 */ function quux (foo) { } // Message: Invalid JSDoc @since: "3.1". /** * @license */ function quux (foo) { } // Message: Missing JSDoc @license value. /** * @license FOO */ function quux (foo) { } // Message: Invalid JSDoc @license: "FOO"; expected SPDX expression: https://spdx.org/licenses/. /** * @license FOO */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"allowedLicenses":["BAR","BAX"]}] // Message: Invalid JSDoc @license: "FOO"; expected one of BAR, BAX. /** * @license MIT-7 * Some extra text... */ function quux (foo) { } // Message: Invalid JSDoc @license: "MIT-7"; expected SPDX expression: https://spdx.org/licenses/. /** * @license (MIT OR GPL-2.5) */ function quux (foo) { } // Message: Invalid JSDoc @license: "(MIT OR GPL-2.5)"; expected SPDX expression: https://spdx.org/licenses/. /** * @license MIT * Some extra text */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"[\\s\\S]*"}] // Message: Invalid JSDoc @license: "MIT Some extra text"; expected SPDX expression: https://spdx.org/licenses/. /** * @author */ function quux (foo) { } // Message: Missing JSDoc @author value. /** * @author Brett Zamir */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"allowedAuthors":["Gajus Kuizinas","golopot"]}] // Message: Invalid JSDoc @author: "Brett Zamir"; expected one of Gajus Kuizinas, golopot. /** * @variation */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"numericOnlyVariation":true}] // Message: Missing JSDoc @variation value. /** * @variation 5.2 */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"numericOnlyVariation":true}] // Message: Invalid JSDoc @variation: "5.2". /** * @license license-prefix Oops */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"(?<=license-prefix ).*"}] // Message: Invalid JSDoc @license: "Oops"; expected SPDX expression: https://spdx.org/licenses/. /** * @license Oops * Copyright 2022 */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"^([^\n]+)\nCopyright"}] // Message: Invalid JSDoc @license: "Oops"; expected SPDX expression: https://spdx.org/licenses/. /** * @import BadImportIgnoredByThisRule */ /** * @import {AnotherBadImportIgnoredByThisRule} from */ // Message: Bad @import tag ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @version 3.4.1 */ function quux (foo) { } /** * @version 3.4.1 */ function quux (foo) { } /** * @since 3.4.1 */ function quux (foo) { } /** * @since 3.4.1 */ function quux (foo) { } /** * @license MIT */ function quux (foo) { } /** * @license MIT * Some extra text... */ function quux (foo) { } /** * @license (MIT OR GPL-2.0) */ function quux (foo) { } /** * @license FOO */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"allowedLicenses":["FOO","BAR","BAX"]}] /** * @license FOO */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"allowedLicenses":true}] /** * @license MIT * Some extra text */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"[^\n]*"}] /** * @author Gajus Kuizinas */ function quux (foo) { } /** * @author Brett Zamir */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"allowedAuthors":["Gajus Kuizinas","golopot","Brett Zamir"]}] /** * @variation 3 */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"numericOnlyVariation":true}] /** * @variation abc */ function quux (foo) { } /** * @module test * @license MIT\r */ 'use strict'; /** * @kind function */ function quux (foo) { } /** * @license license-prefix MIT */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"(?<=license-prefix )MIT|GPL3.0"}] /** * @license * Copyright 2022 */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"^([^\n]+)(?!\nCopyright)"}] /** * @license MIT * Copyright 2022 */ function quux (foo) { } // "jsdoc/check-values": ["error"|"warn", {"licensePattern":"^([^\n]+)\nCopyright"}] /** * @import LinterDef, { Sth as Something, Another as Another2 } from "eslint" */ /** * @import { Linter } from "eslint" */ /** * @import LinterDefault from "eslint" */ /** * @import {Linter as Lintee} from "eslint" */ /** * @import * as Linters from "eslint" */ /** @import { ReactNode } from 'react' */ /** @type {ReactNode} */ export const TEST = null ```` --- # convert-to-jsdoc-comments Converts single line or non-JSDoc, multiline comments into JSDoc comments. Note that this rule is experimental. As usual with fixers, please confirm the results before committing. ## Fixer Converts comments into JSDoc comments. ## Options A single options object has the following properties. ### allowedPrefixes An array of prefixes to allow at the beginning of a comment. Defaults to `['@ts-', 'istanbul ', 'c8 ', 'v8 ', 'eslint', 'prettier-']`. Supplying your own value overrides the defaults. ### contexts The contexts array which will be checked for preceding content. Can either be strings or an object with a `context` string and an optional, default `false` `inlineCommentBlock` boolean. Defaults to `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`, `TSDeclareFunction`. ### contextsAfter The contexts array which will be checked for content on the same line after. Can either be strings or an object with a `context` string and an optional, default `false` `inlineCommentBlock` boolean. Defaults to an empty array. ### contextsBeforeAndAfter The contexts array which will be checked for content before and on the same line after. Can either be strings or an object with a `context` string and an optional, default `false` `inlineCommentBlock` boolean. Defaults to `VariableDeclarator`, `TSPropertySignature`, `PropertyDefinition`. ### enableFixer Set to `false` to disable fixing. ### enforceJsdocLineStyle What policy to enforce on the conversion of non-JSDoc comments without line breaks. (Non-JSDoc (mulitline) comments with line breaks will always be converted to `multi` style JSDoc comments.) - `multi` - Convert to multi-line style ```js /** * Some text */ ``` - `single` - Convert to single-line style ```js /** Some text */ ``` Defaults to `multi`. ### lineOrBlockStyle What style of comments to which to apply JSDoc conversion. - `block` - Applies to block-style comments (`/* ... */`) - `line` - Applies to line-style comments (`// ...`) - `both` - Applies to both block and line-style comments Defaults to `both`. ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`| |Tags|(N/A)| |Recommended|false| |Settings|`minLines`, `maxLines`| |Options|`enableFixer`, `enforceJsdocLineStyle`, `lineOrBlockStyle`, `allowedPrefixes`, `contexts`, `contextsAfter`, `contextsBeforeAndAfter`| ## Failing examples The following patterns are considered problems: ````ts // A single line comment function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single"}] // Message: Line comments should be JSDoc-style. // A single line comment function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contexts":[{"context":"FunctionDeclaration","inlineCommentBlock":true}]}] // Message: Line comments should be JSDoc-style. // A single line comment function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enableFixer":false,"enforceJsdocLineStyle":"single"}] // Message: Line comments should be JSDoc-style. // A single line comment function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single","lineOrBlockStyle":"line"}] // Message: Line comments should be JSDoc-style. /* A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single"}] // Message: Block comments should be JSDoc-style. /* A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single","lineOrBlockStyle":"block"}] // Message: Block comments should be JSDoc-style. // A single line comment function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"multi"}] // Message: Line comments should be JSDoc-style. // A single line comment function quux () {} // Message: Line comments should be JSDoc-style. /* A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"multi"}] // Message: Block comments should be JSDoc-style. // Single line comment function quux() { } // Settings: {"jsdoc":{"structuredTags":{"see":{"name":false,"required":["name"]}}}} // Message: Cannot add "name" to `require` with the tag's `name` set to `false` /* Entity to represent a user in the system. */ @Entity('users', getVal()) export class User { } // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contexts":["ClassDeclaration"]}] // Message: Block comments should be JSDoc-style. /* A single line comment */ function quux () {} // Settings: {"jsdoc":{"maxLines":0,"minLines":0}} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single"}] // Message: Block comments should be JSDoc-style. var a = []; // Test comment // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsAfter":["VariableDeclarator"],"contextsBeforeAndAfter":[]}] // Message: Line comments should be JSDoc-style. var a = []; // Test comment // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsAfter":[{"context":"VariableDeclarator","inlineCommentBlock":true}],"contextsBeforeAndAfter":[]}] // Message: Line comments should be JSDoc-style. var a = []; // Test comment // Settings: {"jsdoc":{"maxLines":0,"minLines":0}} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsAfter":[{"context":"VariableDeclarator","inlineCommentBlock":true}],"contextsBeforeAndAfter":[]}] // Message: Line comments should be JSDoc-style. // Test comment var a = []; // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsBeforeAndAfter":["VariableDeclaration"]}] // Message: Line comments should be JSDoc-style. var a = []; // Test comment // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsBeforeAndAfter":["VariableDeclaration"]}] // Message: Line comments should be JSDoc-style. interface B { g: () => string; // Test comment } // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsBeforeAndAfter":["TSPropertySignature"]}] // Message: Line comments should be JSDoc-style. class TestClass { public Test: (id: number) => string; // Test comment } // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsBeforeAndAfter":["PropertyDefinition"]}] // Message: Line comments should be JSDoc-style. var a = []; // Test comment // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsBeforeAndAfter":["VariableDeclarator"]}] // Message: Line comments should be JSDoc-style. ```` ## Passing examples The following patterns are not considered problems: ````ts /** A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single"}] /** A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"multi"}] /** A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"lineOrBlockStyle":"line"}] /** A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"lineOrBlockStyle":"block"}] /* A single line comment */ function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single","lineOrBlockStyle":"line"}] // A single line comment function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single","lineOrBlockStyle":"block"}] // @ts-expect-error function quux () {} // @custom-something function quux () {} // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"allowedPrefixes":["@custom-"]}] // Test comment var a = []; // "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contextsAfter":["VariableDeclarator"],"contextsBeforeAndAfter":[]}] ```` --- ### empty-tags Expects the following tags to be empty of any content: - `@abstract` - `@async` - `@generator` - `@global` - `@hideconstructor` - `@ignore` - `@inheritdoc` - `@inner` - `@instance` - `@internal` (used by TypeScript) - `@override` - `@readonly` The following will also be expected to be empty unless `settings.jsdoc.mode` is set to "closure" (which allows types). - `@package` - `@private` - `@protected` - `@public` - `@static` Note that `@private` will still be checked for content by this rule even with `settings.jsdoc.ignorePrivate` set to `true` (a setting which normally causes rules not to take effect). Similarly, `@internal` will still be checked for content by this rule even with `settings.jsdoc.ignoreInternal` set to `true`. ## Fixer Strips content if present for the above-mentioned tags. ## Options A single options object has the following properties. ### tags If you want additional tags to be checked for their descriptions, you may add them within this option. ```js { 'jsdoc/empty-tags': ['error', {tags: ['event']}] } ``` ## Context and settings ||| |---|---| |Context|everywhere| |Tags| `abstract`, `async`, `generator`, `global`, `hideconstructor`, `ignore`, `inheritdoc`, `inner`, `instance`, `internal`, `override`, `readonly`, `package`, `private`, `protected`, `public`, `static` and others added by `tags`| |Recommended|true| |Options|`tags`| ## Failing examples The following patterns are considered problems: ````ts /** * @abstract extra text */ function quux () { } // Message: @abstract should be empty. /** * @interface extra text */ // Settings: {"jsdoc":{"mode":"closure"}} // Message: @interface should be empty. class Test { /** * @abstract extra text */ quux () { } } // Message: @abstract should be empty. /** * @abstract extra text * @inheritdoc * @async out of place */ function quux () { } // Message: @abstract should be empty. /** * @event anEvent */ function quux () { } // "jsdoc/empty-tags": ["error"|"warn", {"tags":["event"]}] // Message: @event should be empty. /** * @private {someType} */ function quux () { } // Message: @private should be empty. /** * @internal {someType} */ function quux () { } // Message: @internal should be empty. /** * @private {someType} */ function quux () { } // Settings: {"jsdoc":{"ignorePrivate":true}} // Message: @private should be empty. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @abstract */ function quux () { } /** * */ function quux () { } /** * @param aName */ function quux () { } /** * @abstract * @inheritdoc * @async */ function quux () { } /** * @private {someType} */ function quux () { } // Settings: {"jsdoc":{"mode":"closure"}} /** * @private */ function quux () { } /** * @internal */ function quux () { } /** * Create an array. * * @private * * @param {string[]} [elem] - Elements to make an array of. * @param {boolean} [clone] - Optionally clone nodes. * @returns {string[]} The array of nodes. */ function quux () {} /** Application boot function. @async @private **/ function quux () {} ```` --- # escape-inline-tags Reports use of JSDoc tags in non-tag positions (in the default "typescript" mode). Note that while the JSDoc standard refers to inline tags as those being surrounded by curly brackets, such as those in the form `{@link https://example.com}`, for the purposes of this rule, we are referring to inline tags as a simple reference to tags such as `@param` outside of the normal location of a tag and which may need to be wrapped in `{}` to be proper inline JSDoc or need to be escaped with `\` or wrapped with ` to be normal text. E.g. ```js /** Supports shorthands such as `@yearly` to simplify setup. */ ``` ## Options A single options object has the following properties. ### allowedInlineTags A listing of tags you wish to allow unescaped. Defaults to an empty array. ### enableFixer Whether to enable the fixer. Defaults to `false`. ### fixType How to escape the inline tag. May be "backticks" to enclose tags in backticks (treating as code segments), or "backslash" to escape tags with a backslash, i.e., `\@` Defaults to "backslash". ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|true (unless `mode` is changed away from "typescript")| |Settings|`mode`| |Options|`allowedInlineTags`, `enableFixer`, `fixType`| ## Failing examples The following patterns are considered problems: ````ts /** * * Whether to include a @yearly, @monthly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * Some text * Whether to include a @yearly, @monthly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * Whether to include a @yearly, @yearly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * Whether to include a @yearly, * or @yearly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * Whether to include a @yearly, @monthly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"allowedInlineTags":["monthly"],"enableFixer":true,"fixType":"backticks"}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * Some description @sth */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@sth}, \@sth, or `@sth`? /** * Some description @sth */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":false}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@sth}, \@sth, or `@sth`? /** * @param includeNonStandard Whether to include a @yearly, @monthly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * @param includeNonStandard Whether to include a @yearly, @monthly etc text labels in the generated expression. */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"allowedInlineTags":["monthly"],"enableFixer":true,"fixType":"backticks"}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@yearly}, \@yearly, or `@yearly`? /** * @param aName @sth */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@sth}, \@sth, or `@sth`? /** * @param aName @sth * and @another * @param anotherName @yetAnother */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":true}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@sth}, \@sth, or `@sth`? /** * @param aName @sth */ // "jsdoc/escape-inline-tags": ["error"|"warn", {"enableFixer":false}] // Message: Unexpected inline JSDoc tag. Did you mean to use {@sth}, \@sth, or `@sth`? ```` ## Passing examples The following patterns are not considered problems: ````ts /** * A description with an escaped \@tag. */ /** * A description with a markdown `@tag`. */ /** * A description with a non@tag. */ /** * @param {SomeType} aName A description with an escaped \@tag. */ /** * @param {SomeType} aName A description with a markdown `@tag`. */ /** * @param {SomeType} aName A description with a non@tag. */ /** * {@link https://example.com} */ /** * A description with a {@link https://example.com} */ /** * @someTag {@link https://example.com} */ /** * @param {SomeType} aName {@link https://example.com} */ /** * @param {SomeType} aName A description with a {@link https://example.com}. */ /** * @example * Here are some unescaped tags: @yearly, @monthly */ /** * Whether to include a @yearly, @monthly etc text labels in the generated expression. */ // Settings: {"jsdoc":{"mode":"jsdoc"}} ```` --- # implements-on-classes * [Options](#user-content-implements-on-classes-options) * [`contexts`](#user-content-implements-on-classes-options-contexts) * [Context and settings](#user-content-implements-on-classes-context-and-settings) * [Failing examples](#user-content-implements-on-classes-failing-examples) * [Passing examples](#user-content-implements-on-classes-passing-examples) Reports an issue with any non-constructor function using `@implements`. Constructor functions, whether marked with `@class`, `@constructs`, or being an ES6 class constructor, will not be flagged. To indicate that a function follows another function's signature, one might instead use `@type` to indicate the `@function` or `@callback` to which the function is adhering. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`implements` (prevented)| |Recommended|true| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * @implements {SomeClass} */ function quux () { } // Message: @implements used on a non-constructor function /** * @implements {SomeClass} */ function quux () { } // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["any"]}] // Message: @implements used on a non-constructor function /** * @function * @implements {SomeClass} */ function quux () { } // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["any"]}] // Message: @implements used on a non-constructor function /** * @callback * @implements {SomeClass} */ // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["any"]}] // Message: @implements used on a non-constructor function /** * @implements {SomeClass} */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"implements":false}}} // Message: Unexpected tag `@implements` class Foo { /** * @implements {SomeClass} */ constructor() {} /** * @implements {SomeClass} */ bar() {} } // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["MethodDefinition"]}] // Message: @implements used on a non-constructor function class Foo { /** * @implements {SomeClass} */ constructor() {} /** * @implements {SomeClass} */ bar() {} } // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["any"]}] // Message: @implements used on a non-constructor function ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @implements {SomeClass} * @class */ function quux () { } /** * @implements {SomeClass} * @class */ function quux () { } // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["any"]}] /** * @implements {SomeClass} */ // "jsdoc/implements-on-classes": ["error"|"warn", {"contexts":["any"]}] /** * @implements {SomeClass} * @constructor */ function quux () { } /** * */ class quux { /** * @implements {SomeClass} */ constructor () { } } /** * */ const quux = class { /** * @implements {SomeClass} */ constructor () { } } /** * */ function quux () { } /** * */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"implements":false}}} /** * @function * @implements {SomeClass} */ /** * @callback * @implements {SomeClass} */ ```` --- ### imports-as-dependencies This rule will report an issue if JSDoc `import()` statements point to a package which is not listed in `dependencies` or `devDependencies`. ||| |---|---| |Context|everywhere| |Tags|(Any)| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @type {null|import('sth').SomeApi} */ // Message: import points to package which is not found in dependencies /** * @type {null|import('sth').SomeApi} */ // Settings: {"jsdoc":{"mode":"permissive"}} // Message: import points to package which is not found in dependencies /** * @type {null|import('missingpackage/subpackage').SomeApi} */ // Message: import points to package which is not found in dependencies /** * @type {null|import('@sth/pkg').SomeApi} */ // Message: import points to package which is not found in dependencies /** * @type {null|import('sinon').SomeApi} */ // Message: import points to package which is not found in dependencies ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @type {null|import('eslint').ESLint} */ /** * @type {null|import('eslint/use-at-your-own-risk').ESLint} */ /** * @type {null|import('@es-joy/jsdoccomment').InlineTag} */ /** * @type {null|import(} */ /** * @type {null|import('esquery').ESQueryOptions} */ /** * @type {null|import('@es-joy/jsdoccomment').InlineTag| * import('@es-joy/jsdoccomment').JsdocBlock} */ /** * @type {null|import('typescript').Program} */ /** * @type {null|import('./relativePath.js').Program} */ /** * @type {null|import('fs').PathLike} */ /** * @type {null|import('fs/promises').FileHandle} */ /** * @type {null|import('node:fs').PathLike} */ /** * @type {null|import('playwright').SomeApi} */ /** * @type {null|import('ts-api-utils').SomeApi} */ ```` --- # informative-docs * [Options](#user-content-informative-docs-options) * [`aliases`](#user-content-informative-docs-options-aliases) * [`excludedTags`](#user-content-informative-docs-options-excludedtags) * [`uselessWords`](#user-content-informative-docs-options-uselesswords) * [Context and settings](#user-content-informative-docs-context-and-settings) * [Failing examples](#user-content-informative-docs-failing-examples) * [Passing examples](#user-content-informative-docs-passing-examples) Reports on JSDoc texts that serve only to restate their attached name. Devs sometimes write JSDoc descriptions that add no additional information just to fill out the doc: ```js /** The user id. */ let userId; ``` Those "uninformative" docs comments take up space without being helpful. This rule requires all docs comments contain at least one word not already in the code. ## Options A single options object has the following properties. ### aliases The `aliases` option allows indicating words as synonyms (aliases) of each other. For example, with `{ aliases: { emoji: ["smiley", "winkey"] } }`, the following comment would be considered uninformative: ```js /** A smiley/winkey. */ let emoji; ``` The default `aliases` option is: ```json { "a": ["an", "our"] } ``` ### excludedTags Tags that should not be checked for valid contents. For example, with `{ excludedTags: ["category"] }`, the following comment would not be considered uninformative: ```js /** @category Types */ function computeTypes(node) { // ... } ``` No tags are excluded by default. ### uselessWords Words that are ignored when searching for one that adds meaning. For example, with `{ uselessWords: ["our"] }`, the following comment would be considered uninformative: ```js /** Our text. */ let text; ``` The default `uselessWords` option is: ```json ["a", "an", "i", "in", "of", "s", "the"] ``` ## Context and settings ||| |---|---| |Context|everywhere| |Tags|any| |Recommended|false| |Settings|| |Options|`aliases`, `excludedTags`, `uselessWords`| ## Failing examples The following patterns are considered problems: ````ts /** the */ let myValue = 3; // Message: This description only repeats the name it describes. /** The user id. */ let userId: string; // Message: This description only repeats the name it describes. /** the my value */ let myValue = 3; // Message: This description only repeats the name it describes. /** value **/ let myValue, count = 3; // Message: This description only repeats the name it describes. let myValue, /** count **/ count = 3; // Message: This description only repeats the name it describes. /** * the foo. */ function foo() {} // Message: This description only repeats the name it describes. /** * the value foo. */ const value = function foo() {} // Message: This description only repeats the name it describes. const value = { /** * the prop. */ prop: true, } // Message: This description only repeats the name it describes. /** * name */ class Name {} // Message: This description only repeats the name it describes. /** * abc def */ const abc = class Def {} // Message: This description only repeats the name it describes. class Abc { /** the abc def! */ def; } // Message: This description only repeats the name it describes. const _ = class Abc { /** the abc def! */ def; } // Message: This description only repeats the name it describes. class Abc { /** the abc def! */ def() {}; } // Message: This description only repeats the name it describes. class Abc { /** def */ accessor def; } // Message: This description only repeats the name it describes. class Abc { /** def */ def() {} } // Message: This description only repeats the name it describes. class Abc { /** def */ abstract accessor def; } // Message: This description only repeats the name it describes. class Abc { /** def */ abstract def(); } // Message: This description only repeats the name it describes. class Abc { /** def */ abstract def; } // Message: This description only repeats the name it describes. /** abc */ namespace Abc {} // Message: This description only repeats the name it describes. class Abc { /** def */ def(); def() {} } // Message: This description only repeats the name it describes. /** abc */ declare function abc(); // Message: This description only repeats the name it describes. /** abc */ enum Abc {} // Message: This description only repeats the name it describes. enum Abc { /** def */ def, } // Message: This description only repeats the name it describes. /** def */ interface Def {} // Message: This description only repeats the name it describes. /** def */ type Def = {}; // Message: This description only repeats the name it describes. /** * count * * @description the value */ let value = 3; // Message: This tag description only repeats the name it describes. /** @param {number} param - the param */ function takesOne(param) {} // Message: This tag description only repeats the name it describes. /** @other param - takes one */ function takesOne(param) {} // Message: This tag description only repeats the name it describes. /** * takes one * @other param - takes one */ function takesOne(param) {} // Message: This description only repeats the name it describes. /** * - takes one * @other param - takes one */ function takesOne(param) {} // Message: This description only repeats the name it describes. /** A smiley/winkey. */ let emoji; // "jsdoc/informative-docs": ["error"|"warn", {"aliases":{"emoji":["smiley","winkey"]}}] // Message: This description only repeats the name it describes. /** * package name from path */ export function packageNameFromPath(path) { const base = basename(path); return /^v\d+(\.\d+)?$/.exec(base) || /^ts\d\.\d/.exec(base) ? basename(dirname(path)) : base; } // Message: This description only repeats the name it describes. /** * package name from path */ export default function packageNameFromPath(path) { const base = basename(path); return /^v\d+(\.\d+)?$/.exec(base) || /^ts\d\.\d/.exec(base) ? basename(dirname(path)) : base; } // Message: This description only repeats the name it describes. ```` ## Passing examples The following patterns are not considered problems: ````ts /** */ let myValue = 3; /** count */ let myValue = 3; /** Informative info user id. */ let userId: string; let myValue, /** count value **/ count = 3; /** * Does X Y Z work. */ function foo() {} const value = { /** * the truthiness of the prop. */ prop: true, } const value = { /** * the truthiness of the prop. */ ['prop']: true, } /** * abc def ghi */ const abc = function def() {} /** * name extra */ class Name {} /** * abc name extra */ const abc = class Name {} class Abc { /** ghi */ def; } class Abc { /** ghi */ accessor def; } class Abc { /** ghi */ def() {} } class Abc { /** ghi */ abstract accessor def; } class Abc { /** ghi */ abstract def(); } class Abc { /** ghi */ abstract def; } /** abc */ namespace Def {} class Abc { /** ghi */ def(); def() {} } /** abc */ declare function def(); /** abc */ enum Def {} enum Abc { /** def */ ghi, } /** abc */ interface Def {} /** abc */ type Def = {}; /** abc */ type Def = {}; /** * count * * @description increment value */ let value = 3; /** * count * * @unknownTag - increment value */ let value = 3; /** * @other param - takes one two */ function takesOne(param) {} /** * takes abc param */ function takesOne(param) {} /** * @class * * @param {number} value - Some useful text */ function MyAmazingThing(value) {} /** * My option. * @default {} */ // "jsdoc/informative-docs": ["error"|"warn", {"excludedTags":["default"]}] /** * The */ // "jsdoc/informative-docs": ["error"|"warn", {"uselessWords":["an"]}] ```` --- # lines-before-block This rule enforces minimum number of newlines before JSDoc comment blocks (except at the beginning of a block or file). ## Options A single options object has the following properties. ### checkBlockStarts Whether to additionally check the start of blocks, such as classes or functions. Defaults to `false`. ### excludedTags An array of tags whose presence in the JSDoc block will prevent the application of the rule. Defaults to `['type']` (i.e., if `@type` is present, lines before the block will not be added). ### ignoreSameLine This option excludes cases where the JSDoc block occurs on the same line as a preceding code or comment. Defaults to `true`. ### ignoreSingleLines This option excludes cases where the JSDoc block is only one line long. Defaults to `true`. ### lines The minimum number of lines to require. Defaults to 1. ||| |---|---| |Context|everywhere| |Tags|N/A| |Recommended|false| |Settings|| |Options|`checkBlockStarts`, `excludedTags`, `ignoreSameLine`, `ignoreSingleLines`, `lines`| ## Failing examples The following patterns are considered problems: ````ts someCode; /** * */ // Message: Required 1 line(s) before JSDoc block someCode; /** * */ // "jsdoc/lines-before-block": ["error"|"warn", {"ignoreSameLine":false}] // Message: Required 1 line(s) before JSDoc block someCode; /** */ // "jsdoc/lines-before-block": ["error"|"warn", {"ignoreSameLine":false,"ignoreSingleLines":false}] // Message: Required 1 line(s) before JSDoc block someCode; /** * */ // "jsdoc/lines-before-block": ["error"|"warn", {"lines":2}] // Message: Required 2 line(s) before JSDoc block // Some comment /** * */ // Message: Required 1 line(s) before JSDoc block /* Some comment */ /** * */ // Message: Required 1 line(s) before JSDoc block /** * Some comment */ /** * */ // Message: Required 1 line(s) before JSDoc block { /** * Description. */ let value; } // "jsdoc/lines-before-block": ["error"|"warn", {"checkBlockStarts":true}] // Message: Required 1 line(s) before JSDoc block class MyClass { /** * Description. */ method() {} } // "jsdoc/lines-before-block": ["error"|"warn", {"checkBlockStarts":true}] // Message: Required 1 line(s) before JSDoc block function myFunction() { /** * Description. */ let value; } // "jsdoc/lines-before-block": ["error"|"warn", {"checkBlockStarts":true}] // Message: Required 1 line(s) before JSDoc block const values = [ /** * Description. */ value, ]; // "jsdoc/lines-before-block": ["error"|"warn", {"checkBlockStarts":true}] // Message: Required 1 line(s) before JSDoc block const values = [ value1, /** * Description. */ value2 ]; // Message: Required 1 line(s) before JSDoc block const values = [ value1, value2 ] /** * Description. */ // Message: Required 1 line(s) before JSDoc block const value = 123 /** * Description. */ // Message: Required 1 line(s) before JSDoc block type UnionDocumentation = /** Description. */ | { someProp: number } /** Description. */ | { otherProp: string } type IntersectionDocumentation = /** Description. */ { someProp: number } & /** Description. */ { otherProp: string } // "jsdoc/lines-before-block": ["error"|"warn", {"ignoreSingleLines":false}] // Message: Required 1 line(s) before JSDoc block type IntersectionDocumentation = { someProp: number; } & /** Description. */ { otherProp: string; }; // "jsdoc/lines-before-block": ["error"|"warn", {"ignoreSameLine":false,"ignoreSingleLines":false}] // Message: Required 1 line(s) before JSDoc block /** The parameters for a request */ export type RequestParams = { /** The year to retrieve. */ year: `${number}`; /** * The month to retrieve. */ month: `${number}`; } // "jsdoc/lines-before-block": ["error"|"warn", {"ignoreSingleLines":true}] // Message: Required 1 line(s) before JSDoc block ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ someCode; /** * */ someCode; /** * */ // "jsdoc/lines-before-block": ["error"|"warn", {"lines":2}] // Some comment /** * */ /* Some comment */ /** * */ /** * Some comment */ /** * */ someCode; /** */ const a = { someProp: /** @type {SomeCast} */ (someVal) }; const a = /** @lends SomeClass */ { someProp: (someVal) }; // "jsdoc/lines-before-block": ["error"|"warn", {"excludedTags":["lends"],"ignoreSameLine":false}] { /** * Description. */ let value; } class MyClass { /** * Description. */ method() {} } function myFunction() { /** * Description. */ let value; } class SomeClass { constructor( /** * Description. */ param ) {}; method( /** * Description. */ param ) {}; } type FunctionAlias1 = /** * @param param - Description. */ (param: number) => void; type FunctionAlias2 = ( /** * @param param - Description. */ param: number ) => void; type UnionDocumentation = /** Description. */ | { someProp: number } /** Description. */ | { otherProp: string } type IntersectionDocumentation = /** Description. */ { someProp: number } & /** Description. */ { otherProp: string } type IntersectionDocumentation = { someProp: number; } & /** Description. */ { otherProp: string; }; /** The parameters for a request */ export type RequestParams = { /** The year to retrieve. */ year: `${number}`; /** The month to retrieve. */ month: `${number}`; } // "jsdoc/lines-before-block": ["error"|"warn", {"ignoreSingleLines":true}] ```` --- # match-description * [Options](#user-content-match-description-options) * [`contexts`](#user-content-match-description-options-contexts) * [`mainDescription`](#user-content-match-description-options-maindescription) * [`matchDescription`](#user-content-match-description-options-matchdescription) * [`message`](#user-content-match-description-options-message) * [`nonemptyTags`](#user-content-match-description-options-nonemptytags) * [`tags`](#user-content-match-description-options-tags) * [Context and settings](#user-content-match-description-context-and-settings) * [Failing examples](#user-content-match-description-failing-examples) * [Passing examples](#user-content-match-description-passing-examples) Enforces a regular expression pattern on descriptions. The default is this basic expression to match English sentences (Support for Unicode upper case may be added in a future version when it can be handled by our supported Node versions): ``^\n?([A-Z`\\d_][\\s\\S]*[.?!`\\p{RGI_Emoji}]\\s*)?$`` Applies by default to the JSDoc block description and to the following tags: - `@description`/`@desc` - `@summary` - `@file`/`@fileoverview`/`@overview` - `@classdesc` In addition, the `tags` option (see below) may be used to match other tags. The default (and all regex options) defaults to using (only) the `v` flag, so to add your own flags, encapsulate your expression as a string, but like a literal, e.g., `/[A-Z].*\\./vi`. Note that `/` delimiters are optional, but necessary to add flags (besides `v`). Also note that the default or optional regular expressions is *not* case-insensitive unless one opts in to add the `i` flag. You can add the `s` flag if you want `.` to match newlines. Note, however, that the trailing newlines of a description will not be matched. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied (e.g., `ClassDeclaration` for ES6 classes). `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files. See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### mainDescription If you wish to override the main block description without changing the default `match-description` (which can cascade to the `tags` with `true`), you may use `mainDescription`: ```js { 'jsdoc/match-description': ['error', { mainDescription: '[A-Z].*\\.', tags: { param: true, returns: true } }] } ``` There is no need to add `mainDescription: true`, as by default, the main block description (and only the main block description) is linted, though you may disable checking it by setting it to `false`. You may also provide an object with `message`: ```js { 'jsdoc/match-description': ['error', { mainDescription: { message: 'Capitalize first word of JSDoc block descriptions', match: '[A-Z].*\\.' }, tags: { param: true, returns: true } }] } ``` ### matchDescription You can supply your own expression to override the default, passing a `matchDescription` string on the options object. Defaults to using (only) the `v` flag, so to add your own flags, encapsulate your expression as a string, but like a literal, e.g., `/[A-Z].*\./vi`. ```js { 'jsdoc/match-description': ['error', {matchDescription: '[A-Z].*\\.'}] } ``` ### message You may provide a custom default message by using the following format: ```js { 'jsdoc/match-description': ['error', { message: 'The default description should begin with a capital letter.' }] } ``` This can be overridden per tag or for the main block description by setting `message` within `tags` or `mainDescription`, respectively. ### nonemptyTags If not set to `false`, will enforce that the following tags have at least some content: - `@copyright` - `@example` - `@see` - `@todo` If you supply your own tag description for any of the above tags in `tags`, your description will take precedence. ### tags If you want different regular expressions to apply to tags, you may use the `tags` option object: ```js { 'jsdoc/match-description': ['error', {tags: { param: '\\- [A-Z].*\\.', returns: '[A-Z].*\\.' }}] } ``` In place of a string, you can also add `true` to indicate that a particular tag should be linted with the `matchDescription` value (or the default). ```js { 'jsdoc/match-description': ['error', {tags: { param: true, returns: true }}] } ``` Alternatively, you may supply an object with a `message` property to indicate the error message for that tag. ```js { 'jsdoc/match-description': ['error', {tags: { param: {message: 'Begin with a hyphen', match: '\\- [A-Z].*\\.'}, returns: {message: 'Capitalize for returns (the default)', match: true} }}] } ``` The tags `@param`/`@arg`/`@argument` and `@property`/`@prop` will be properly parsed to ensure that the matched "description" text includes only the text after the name. All other tags will treat the text following the tag name, a space, and an optional curly-bracketed type expression (and another space) as part of its "description" (e.g., for `@returns {someType} some description`, the description is `some description` while for `@some-tag xyz`, the description is `xyz`). ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|docblock and `@description` by default but more with `tags`| |Aliases|`@desc`| |Recommended|false| |Settings|| |Options|`contexts`, `mainDescription`, `matchDescription`, `message`, `nonemptyTags`, `tags`| ## Failing examples The following patterns are considered problems: ````ts /** * foo. */ const q = class { } // "jsdoc/match-description": ["error"|"warn", {"contexts":["ClassExpression"]}] // Message: JSDoc description does not satisfy the regex pattern. /** * foo. */ const q = class { } // "jsdoc/match-description": ["error"|"warn", {"contexts":["ClassExpression"],"message":"Needs to begin with a capital letter and end with an end mark."}] // Message: Needs to begin with a capital letter and end with an end mark. /** * foo. */ // "jsdoc/match-description": ["error"|"warn", {"contexts":["any"]}] // Message: JSDoc description does not satisfy the regex pattern. /** * foo. */ const q = { }; // "jsdoc/match-description": ["error"|"warn", {"contexts":["ObjectExpression"]}] // Message: JSDoc description does not satisfy the regex pattern. /** * foo. */ function quux () { } // Message: JSDoc description does not satisfy the regex pattern. /** * Foo) */ function quux () { } // Message: JSDoc description does not satisfy the regex pattern. /** * тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"matchDescription":"[А-Я][А-я]+\\."}] // Message: JSDoc description does not satisfy the regex pattern. /** * тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"matchDescription":"[А-Я][А-я]+\\.","message":"Needs to begin with a capital letter and end with an end mark."}] // Message: Needs to begin with a capital letter and end with an end mark. /** * Abc. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":"[А-Я][А-я]+\\.","tags":{"param":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Abc. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":{"match":"[А-Я][А-я]+\\.","message":"Needs to begin with a Cyrillic capital letter and end with a period."},"tags":{"param":true}}] // Message: Needs to begin with a Cyrillic capital letter and end with a period. /** * Foo */ function quux () { } // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @param foo foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"param":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @template Abc, Def foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"template":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @prop foo foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"prop":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @summary foo. */ function quux () { } // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @author */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"author":".+"}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @x-tag */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"x-tag":".+"}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @description foo foo. */ function quux (foo) { } // Message: JSDoc description does not satisfy the regex pattern. /** * Foo * * @param foo foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":"^[a-zA-Z]*\\s*$","tags":{"param":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo * * @param foo foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":{"match":"^[a-zA-Z]*\\s*$","message":"Letters only"},"tags":{"param":{"match":true,"message":"Needs to begin with a capital letter and end with a period."}}}] // Message: Needs to begin with a capital letter and end with a period. /** * Foo * * @param foo foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":false,"tags":{"param":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @param foo bar */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"param":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * {@see Foo.bar} buz */ function quux (foo) { } // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @returns {number} foo */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"returns":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo. * * @returns foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"returns":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * lorem ipsum dolor sit amet, consectetur adipiscing elit. pellentesque elit diam, * iaculis eu dignissim sed, ultrices sed nisi. nulla at ligula auctor, consectetur neque sed, * tincidunt nibh. vivamus sit amet vulputate ligula. vivamus interdum elementum nisl, * vitae rutrum tortor semper ut. morbi porta ante vitae dictum fermentum. * proin ut nulla at quam convallis gravida in id elit. sed dolor mauris, blandit quis ante at, * consequat auctor magna. duis pharetra purus in porttitor mollis. */ function longDescription (foo) { } // Message: JSDoc description does not satisfy the regex pattern. /** * @arg {number} foo - Foo */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"arg":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * @argument {number} foo - Foo */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"argument":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * @return {number} foo */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"return":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Returns bar. * * @return {number} bar */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"return":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * @param notRet * @returns Тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"param":"[А-Я][А-я]+\\."}}] // Message: JSDoc description does not satisfy the regex pattern. /** * @description notRet * @returns Тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"description":"[А-Я][А-я]+\\."}}] // Message: JSDoc description does not satisfy the regex pattern. /** * foo. */ class quux { } // "jsdoc/match-description": ["error"|"warn", {"contexts":["ClassDeclaration"]}] // Message: JSDoc description does not satisfy the regex pattern. class MyClass { /** * Abc */ myClassField = 1 } // "jsdoc/match-description": ["error"|"warn", {"contexts":["PropertyDefinition"]}] // Message: JSDoc description does not satisfy the regex pattern. /** * foo. */ interface quux { } // "jsdoc/match-description": ["error"|"warn", {"contexts":["TSInterfaceDeclaration"]}] // Message: JSDoc description does not satisfy the regex pattern. const myObject = { /** * Bad description */ myProp: true }; // "jsdoc/match-description": ["error"|"warn", {"contexts":["Property"]}] // Message: JSDoc description does not satisfy the regex pattern. /** * @param foo Foo bar */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} // "jsdoc/match-description": ["error"|"warn", {"tags":{"param":true}}] // Message: JSDoc description does not satisfy the regex pattern. /** * Foo bar */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} // Message: JSDoc description does not satisfy the regex pattern. /** * Description with extra new line * */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"matchDescription":"[\\s\\S]*\\S$"}] // Message: JSDoc description does not satisfy the regex pattern. /** * * This function does lots of things. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"matchDescription":"^\\S[\\s\\S]*\\S$"}] // Message: JSDoc description does not satisfy the regex pattern. /** * * @param */ // "jsdoc/match-description": ["error"|"warn", {"contexts":["any"],"matchDescription":"^\\S[\\s\\S]*\\S$"}] // Message: JSDoc description does not satisfy the regex pattern. /** Does something very important. */ function foo(): string; // "jsdoc/match-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[endLine=0]"}],"matchDescription":"^\\S[\\s\\S]*\\S$"}] // Message: JSDoc description does not satisfy the regex pattern. /** * @copyright */ function quux () { } // Message: JSDoc description must not be empty. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ /** * */ function quux () { } /** * @param foo - Foo. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"param":true}}] /** * Foo. */ function quux () { } /** * Foo. * Bar. */ function quux () { } /** * Foo. * * Bar. */ function quux () { } /** * Foo. * * Bar. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"message":"This won't be shown"}] /** * Тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"matchDescription":"[А-Я][А-я]+\\."}] /** * @param notRet * @returns Тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"returns":"[А-Я][А-я]+\\."}}] /** * @param notRet * @description Тест. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"description":"[А-Я][А-я]+\\."}}] /** * Foo * bar. */ function quux () { } /** * @returns Foo bar. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"returns":true}}] /** * @returns {type1} Foo bar. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"returns":true}}] /** * @description Foo bar. */ function quux () { } /** * @description Foo * bar. * @param */ function quux () { } /** @description Foo bar. */ function quux () { } /** * @description Foo * bar. */ function quux () { } /** * Foo. {@see Math.sin}. */ function quux () { } /** * Foo {@see Math.sin} bar. */ function quux () { } /** * Foo? * * Bar! * * Baz: * 1. Foo. * 2. Bar. */ function quux () { } /** * Hello: * World. */ function quux () { } /** * Hello: world. */ function quux () { } /** * Foo * Bar. */ function quux () { } /** * Foo. * * foo. */ function quux () { } /** * foo. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":false}] /** * foo. */ class quux { } /** * foo. */ class quux { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":true}] class MyClass { /** * Abc. */ myClassField = 1 } // "jsdoc/match-description": ["error"|"warn", {"contexts":["PropertyDefinition"]}] /** * Foo. */ interface quux { } // "jsdoc/match-description": ["error"|"warn", {"contexts":["TSInterfaceDeclaration"]}] const myObject = { /** * Bad description */ myProp: true }; // "jsdoc/match-description": ["error"|"warn", {"contexts":[]}] /** * foo. */ const q = class { } // "jsdoc/match-description": ["error"|"warn", {"contexts":[]}] /** * foo. */ const q = { }; // "jsdoc/match-description": ["error"|"warn", {"contexts":[]}] /** * @deprecated foo. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"param":true}}] /** * Foo. * * @summary Foo. */ function quux () { } /** * Foo. * * @author Somebody */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"author":".+"}}] /** * Foo. * * @x-tag something */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"x-tag":".+"}}] /** * Foo. * * @prop foo Foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"prop":true}}] /** * @param foo Foo bar. */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} /** * */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} /** * Foo. * * @template Abc, Def Foo. */ function quux (foo) { } // "jsdoc/match-description": ["error"|"warn", {"tags":{"template":true}}] /** * Enable or disable plugin. * * When enabling with this function, the script will be attached to the `document` if:. * - the script runs in browser context. * - the `document` doesn't have the script already attached. * - the `loadScript` option is set to `true`. * @param enabled `true` to enable, `false` to disable. Default: `true`. */ // "jsdoc/match-description": ["error"|"warn", {"contexts":["any"],"mainDescription":"/^[A-Z`\\-].*\\.$/vs","matchDescription":"^([A-Z`\\-].*(\\.|:)|-\\s.*)$","tags":{"param":true,"returns":true}}] /** * @constructor * @todo Ok. */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"mainDescription":false,"tags":{"todo":true}}] /** Does something very important. */ function foo(): string; // "jsdoc/match-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[endLine!=0]"}],"matchDescription":"^\\S[\\s\\S]*\\S$"}] /** * This is my favorite function, foo. * * @returns Nothing. */ function foo(): void; // "jsdoc/match-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[endLine!=0]:not(:has(JsdocTag))"}],"matchDescription":"^\\S[\\s\\S]*\\S$"}] /** * @copyright */ function quux () { } // "jsdoc/match-description": ["error"|"warn", {"nonemptyTags":false}] /** * Example text. 🙂 */ export const example = () => { }; ```` --- ### match-name Reports the name portion of a JSDoc tag if matching or not matching a given regular expression. Note that some tags do not possess names and anything appearing to be a name will actually be part of the description (e.g., for `@returns {type} notAName`). If you are defining your own tags, see the `structuredTags` setting (if `name: false`, this rule will not apply to that tag). ## Fixer Will replace `disallowName` with `replacement` if these are provided. ## Options A single options object has the following properties. ### match `match` is a required option containing an array of objects which determine the conditions whereby a name is reported as being problematic. These objects can have any combination of the following groups of optional properties, all of which act to confine one another. Note that `comment`, even if targeting a specific tag, is used to match the whole block. So if a `comment` finds its specific tag, it may still apply fixes found by the likes of `disallowName` even when a different tag has the disallowed name. An alternative is to ensure that `comment` finds the specific tag of the desired tag and/or name and no `disallowName` (or `allowName`) is supplied. In such a case, only one error will be reported, but no fixer will be applied, however. A single options object has the following properties. ##### allowName Indicates which names are allowed for the given tag (or `*`). Accepts a string regular expression (optionally wrapped between two `/` delimiters followed by optional flags) used to match the name. ##### comment As with `context` but AST for the JSDoc block comment and types. ##### context AST to confine the allowing or disallowing to JSDoc blocks associated with a particular context. See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ##### disallowName As with `allowName` but indicates names that are not allowed. ##### message An optional custom message to use when there is a match. ##### replacement If `disallowName` is supplied and this value is present, it will replace the matched `disallowName` text. ##### tags This array should include tag names or `*` to indicate the match will apply for all tags (except as confined by any context properties). If `*` is not used, then these rules will only apply to the specified tags. If `tags` is omitted, then `*` is assumed. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|(The tags specified by `tags`, including any tag if `*` is set)| |Recommended|false| |Settings|`structuredTags`| |Options|`match`| ## Failing examples The following patterns are considered problems: ````ts /** * @param opt_a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i"}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_a". /** * @param opt_a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","replacement":""}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_a". /** * @param a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z]+$/i"}]}] // Message: Only allowing names matching `/^[a-z]+$/i` but found "opt_b". /** * @param arg * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z]+$/i","disallowName":"/^arg/i"}]}] // Message: Only allowing names not matching `/^arg/i` but found "arg". /** * @param opt_a * @param arg */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg$/i"},{"disallowName":"/^opt_/i"}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_a". /** * @property opt_a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["param"]}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_b". /** * @someTag opt_a * @param opt_b */ // Settings: {"jsdoc":{"structuredTags":{"someTag":{"name":"namepath-defining"}}}} // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["param"]}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_b". /** * @property opt_a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["*"]}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_a". /** * @param opt_a * @param opt_b */ function quux () { } // "jsdoc/match-name": ["error"|"warn", {"match":[{"context":"FunctionDeclaration","disallowName":"/^opt_/i"}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_a". /** * @property opt_a * @param {Bar|Foo} opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"comment":"JsdocBlock:has(JsdocTag[tag=\"param\"][name=/opt_/] > JsdocTypeUnion:has(JsdocTypeName[value=\"Bar\"]:nth-child(1)))"}]}] // Message: Prohibited context for "opt_a". /** * @property opt_a * @param {Bar|Foo} opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"comment":"JsdocBlock:has(JsdocTag[tag=\"param\"][name=/opt_/] > JsdocTypeUnion:has(JsdocTypeName[value=\"Bar\"]:nth-child(1)))","message":"Don't use `opt_` prefixes with Bar|..."}]}] // Message: Don't use `opt_` prefixes with Bar|... /** * @param opt_a * @param opt_b */ function quux () {} // "jsdoc/match-name": ["error"|"warn", ] // Message: Rule `no-restricted-syntax` is missing a `match` option. /** * @param { * someType * } opt_a */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","replacement":""}]}] // Message: Only allowing names not matching `/^opt_/i` but found "opt_a". /** * @template */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^$/","tags":["template"]}]}] // Message: Only allowing names not matching `/^$/v` but found "". ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param opt_a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg/i"}]}] /** * @param a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z_]+$/i"}]}] /** * @param someArg * @param anotherArg */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[a-z]+$/i","disallowName":"/^arg/i"}]}] /** * @param elem1 * @param elem2 */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg$/i"},{"disallowName":"/^opt_/i"}]}] /** * @someTag opt_a * @param opt_b */ // Settings: {"jsdoc":{"structuredTags":{"someTag":{"name":"namepath-defining"}}}} // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^opt_/i","tags":["property"]}]}] /** * @property opt_a * @param opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"disallowName":"/^arg/i","tags":["*"]}]}] /** * @param opt_a * @param opt_b */ class A { } // "jsdoc/match-name": ["error"|"warn", {"match":[{"context":"FunctionDeclaration","disallowName":"/^opt_/i"}]}] /** * @property opt_a * @param {Foo|Bar} opt_b */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"comment":"JsdocBlock:has(JsdocTag[tag=\"param\"]:has(JsdocTypeUnion:has(JsdocTypeName[value=\"Bar\"]:nth-child(1))))","disallowName":"/^opt_/i"}]}] /** * @template {string} [T=typeof FOO] * @typedef {object} Test * @property {T} test */ // "jsdoc/match-name": ["error"|"warn", {"match":[{"allowName":"/^[A-Z]{1}$/","message":"The name should be a single capital letter.","tags":["template"]}]}] ```` --- ### multiline-blocks Controls how and whether JSDoc blocks can be expressed as single or multiple line blocks. Note that if you set `noSingleLineBlocks` and `noMultilineBlocks` to `true` and configure them in a certain manner, you might effectively be prohibiting all JSDoc blocks! Also allows for preventing text at the very beginning or very end of blocks. ## Fixer Optionally converts single line blocks to multiline ones and vice versa. ## Options A single options object has the following properties. ### allowMultipleTags If `noMultilineBlocks` is set to `true` with this option and multiple tags are found in a block, an error will not be reported. Since multiple-tagged lines cannot be collapsed into a single line, this option prevents them from being reported. Set to `false` if you really want to report any blocks. This option will also be applied when there is a block description and a single tag (since a description cannot precede a tag on a single line, and also cannot be reliably added after the tag either). Defaults to `true`. ### minimumLengthForMultiline If `noMultilineBlocks` is set with this numeric option, multiline blocks will be permitted if containing at least the given amount of text. If not set, multiline blocks will not be permitted regardless of length unless a relevant tag is present and `multilineTags` is set. Defaults to not being in effect. ### multilineTags If `noMultilineBlocks` is set with this option, multiline blocks may be allowed regardless of length as long as a tag or a tag of a certain type is present. If `*` is included in the array, the presence of a tags will allow for multiline blocks (but not when without any tags unless the amount of text is over an amount specified by `minimumLengthForMultiline`). If the array does not include `*` but lists certain tags, the presence of such a tag will cause multiline blocks to be allowed. You may set this to an empty array to prevent any tag from permitting multiple lines. Defaults to `['*']`. ### noFinalLineText For multiline blocks, any non-whitespace text preceding the `*/` on the final line will be reported. (Text preceding a newline is not reported.) `noMultilineBlocks` will have priority over this rule if it applies. Defaults to `true`. ### noMultilineBlocks Requires that JSDoc blocks are restricted to single lines only unless impacted by the options `minimumLengthForMultiline`, `multilineTags`, or `allowMultipleTags`. Defaults to `false`. ### noSingleLineBlocks If this is `true`, any single line blocks will be reported, except those which are whitelisted in `singleLineTags`. Defaults to `false`. ### noZeroLineText For multiline blocks, any non-whitespace text immediately after the `/**` and space will be reported. (Text after a newline is not reported.) `noMultilineBlocks` will have priority over this rule if it applies. Defaults to `true`. ### requireSingleLineUnderCount If this number is set, it indicates a minimum line width for a single line of JSDoc content spread over a multi-line comment block. If a single line is under the minimum length, it will be reported so as to enforce single line JSDoc blocks for such cases. Blocks are not reported which have multi-line descriptions, multiple tags, a block description and tag, or tags with multi-line types or descriptions. Defaults to `null`. ### singleLineTags An array of tags which can nevertheless be allowed as single line blocks when `noSingleLineBlocks` is set. You may set this to a empty array to cause all single line blocks to be reported. If `'*'` is present, then the presence of a tag will allow single line blocks (but not if a tag is missing). Defaults to `['lends', 'type']`. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|Any (though `singleLineTags` and `multilineTags` control the application)| |Recommended|true| |Settings|| |Options|`allowMultipleTags`, `minimumLengthForMultiline`, `multilineTags`, `noFinalLineText`, `noMultilineBlocks`, `noSingleLineBlocks`, `noZeroLineText`, `requireSingleLineUnderCount`, `singleLineTags`| ## Failing examples The following patterns are considered problems: ````ts /** Reported up here * because the rest is multiline */ // Message: Should have no text on the "0th" line (after the `/**`). /** Reported up here * because the rest is multiline */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noZeroLineText":true}] // Message: Should have no text on the "0th" line (after the `/**`). /** @abc {aType} aName Reported up here * because the rest is multiline */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noZeroLineText":true}] // Message: Should have no text on the "0th" line (after the `/**`). /** @tag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true}] // Message: Single line blocks are not permitted by your configuration. /** @tag {someType} */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true}] // Message: Single line blocks are not permitted by your configuration. /** @tag {someType} aName */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true}] // Message: Single line blocks are not permitted by your configuration. /** @tag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true,"singleLineTags":["someOtherTag"]}] // Message: Single line blocks are not permitted by your configuration. /** desc */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true,"singleLineTags":["*"]}] // Message: Single line blocks are not permitted by your configuration. /** * Desc. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** desc * */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** desc * */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true,"noSingleLineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration but fixing would result in a single line block which you have prohibited with `noSingleLineBlocks`. /** * */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * This is not long enough to be permitted. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"minimumLengthForMultiline":100,"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * This is not long enough to be permitted. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":true,"minimumLengthForMultiline":100,"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * This has the wrong tags so is not permitted. * @notTheRightTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":false,"multilineTags":["onlyThisIsExempted"],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration but the block has a description with a tag. /** * This has too many tags so cannot be fixed ot a single line. * @oneTag * @anotherTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":false,"multilineTags":[],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration but the block has multiple tags. /** * This has a tag and description so cannot be fixed ot a single line. * @oneTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":false,"multilineTags":[],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration but the block has a description with a tag. /** * This has no tags so is not permitted. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":["*"],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * This has the wrong tags so is not permitted. * @notTheRightTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":false,"minimumLengthForMultiline":500,"multilineTags":["onlyThisIsExempted"],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration but the block has a description with a tag. /** * @lends This can be safely fixed to a single line. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":[],"noMultilineBlocks":true,"noSingleLineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * @type {aType} This can be safely fixed to a single line. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":[],"noMultilineBlocks":true,"noSingleLineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * @aTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":[],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * This is a problem when single and multiline are blocked. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true,"noSingleLineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration but fixing would result in a single line block which you have prohibited with `noSingleLineBlocks`. /** This comment is bad * It should not have text on line zero */ // "jsdoc/multiline-blocks": ["error"|"warn", {"minimumLengthForMultiline":50,"noMultilineBlocks":true,"noZeroLineText":true}] // Message: Should have no text on the "0th" line (after the `/**`). /** * @lends This can be safely fixed * to a single * line. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":[],"noMultilineBlocks":true}] // Message: Multiline JSDoc blocks are prohibited by your configuration. /** * @someTag {aType} with Description */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noFinalLineText":true}] // Message: Should have no text on the final line (before the `*/`). /** * Description */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noFinalLineText":true}] // Message: Should have no text on the final line (before the `*/`). /** * Description too short */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] // Message: Description is too short to be multi-line. /** Description too short */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] // Message: Description is too short to be multi-line. /** * Description too short */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] // Message: Description is too short to be multi-line. /** * @someTag {someType} Description too short */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] // Message: Description is too short to be multi-line. /** @someTag {someType} Description too short */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] // Message: Description is too short to be multi-line. /** * @someTag {someType} Description too short */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] // Message: Description is too short to be multi-line. ```` ## Passing examples The following patterns are not considered problems: ````ts /** Not reported */ /** * Not reported */ /** Reported up here * because the rest is multiline */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noZeroLineText":false}] /** @tag */ /** @lends */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true}] /** @tag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true,"singleLineTags":["tag"]}] /** @tag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noSingleLineBlocks":true,"singleLineTags":["*"]}] /** * */ /** * */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":false}] /** Test */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true}] /** * This is long enough to be permitted by our config. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"minimumLengthForMultiline":25,"noMultilineBlocks":true}] /** * This is long enough to be permitted by our config. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"minimumLengthForMultiline":50,"noMultilineBlocks":true}] /** * This has the right tag so is permitted. * @theRightTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":["theRightTag"],"noMultilineBlocks":true}] /** This has no tags but is single line so is not permitted. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":["*"],"noMultilineBlocks":true}] /** * This has the wrong tags so is not permitted. * @notTheRightTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"minimumLengthForMultiline":10,"multilineTags":["onlyThisIsExempted"],"noMultilineBlocks":true}] /** * This has the wrong tags so is not permitted. * @theRightTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"minimumLengthForMultiline":500,"multilineTags":["theRightTag"],"noMultilineBlocks":true}] /** tag */ /** * @lends This is ok per multiline */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noMultilineBlocks":true,"noSingleLineBlocks":true}] /** * This has too many tags so cannot be fixed ot a single line. * @oneTag * @anotherTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"multilineTags":[],"noMultilineBlocks":true}] /** * This has too many tags so cannot be fixed ot a single line. * @oneTag * @anotherTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":true,"multilineTags":[],"noMultilineBlocks":true}] /** * This has a tag and description so cannot be fixed ot a single line. * @oneTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":true,"multilineTags":[],"noMultilineBlocks":true}] /** * This has a tag and description so cannot be fixed ot a single line. * @oneTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"allowMultipleTags":false,"multilineTags":["oneTag"],"noMultilineBlocks":true}] /** @someTag with Description */ // "jsdoc/multiline-blocks": ["error"|"warn", {"noFinalLineText":true}] /** * This description here is very much long enough, I'd say, wouldn't you? */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** * This description here is * on multiple lines. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** This description here is on a single line, so it doesn't matter if it goes over. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** * @someTag {someType} This description here is very much long enough, I'd say, wouldn't you? */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** * @someTag {someType} This description here is * on multiple lines. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** @someTag {someTag} This description here is on a single line, so it doesn't matter if it goes over. */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** * Description short but has... * @someTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** * @someTag * @anotherTag */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":80}] /** * @type {{ visible: import("vue").Ref, attack: import("vue").Ref, hero: import("vue").Ref, outpost: import("vue").Ref, rewards: import("vue").Ref * }} */ // "jsdoc/multiline-blocks": ["error"|"warn", {"requireSingleLineUnderCount":120}] ```` --- ### no-bad-blocks This rule checks for multi-line-style comments which fail to meet the criteria of a JSDoc block, namely that it should begin with two and only two asterisks, but which appear to be intended as JSDoc blocks due to the presence of whitespace followed by whitespace or asterisks, and an at-sign (`@`) and some non-whitespace (as with a JSDoc block tag). Exceptions are made for ESLint directive comments (which may use `@` in rule names). ## Fixer Repairs badly-formed blocks missing two initial asterisks. ## Options A single options object has the following properties. ### ignore An array of directives that will not be reported if present at the beginning of a multi-comment block and at-sign `/* @`. Defaults to `['ts-check', 'ts-expect-error', 'ts-ignore', 'ts-nocheck']` (some directives [used by TypeScript](https://www.typescriptlang.org/docs/handbook/intro-to-js-ts.html#ts-check)). ### preventAllMultiAsteriskBlocks A boolean (defaulting to `false`) which if `true` will prevent all JSDoc-like blocks with more than two initial asterisks even those without apparent tag content. ## Context and settings ||| |---|---| |Context|Everywhere| |Tags|N/A| |Recommended|false| |Options|`ignore`, `preventAllMultiAsteriskBlocks`| ## Failing examples The following patterns are considered problems: ````ts /* * @param foo */ function quux (foo) { } // Message: Expected JSDoc-like comment to begin with two asterisks. /* * @property foo */ // Message: Expected JSDoc-like comment to begin with two asterisks. function quux() { } // Settings: {"jsdoc":{"structuredTags":{"see":{"name":false,"required":["name"]}}}} // Message: Cannot add "name" to `require` with the tag's `name` set to `false` /* @ts-ignore */ // "jsdoc/no-bad-blocks": ["error"|"warn", {"ignore":[]}] // Message: Expected JSDoc-like comment to begin with two asterisks. /* * Some description. * * @returns {string} Some string */ function echo() { return 'Something'; } // Message: Expected JSDoc-like comment to begin with two asterisks. /*** * @param foo */ function quux (foo) { } // Message: Expected JSDoc-like comment to begin with two asterisks. /*** * */ function quux (foo) { } // "jsdoc/no-bad-blocks": ["error"|"warn", {"preventAllMultiAsteriskBlocks":true}] // Message: Expected JSDoc-like comment to begin with two asterisks. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @property foo */ /** * @param foo */ function quux () { } function quux () { } /* This could just be intended as a regular multiline comment, so don't report this */ function quux () { } /* Just a regular multiline comment with an `@` but not appearing like a tag in a jsdoc-block, so don't report */ function quux () { } /* @ts-check */ /* @ts-expect-error */ /* @ts-ignore */ /* @ts-nocheck */ /* */ /** */ /* @custom */ // "jsdoc/no-bad-blocks": ["error"|"warn", {"ignore":["custom"]}] /*** * This is not JSDoc because of the 3 asterisks, but * is allowed without `preventAllMultiAsteriskBlocks`, as * some might wish normal multiline comments. */ function quux (foo) { } /***/ /* eslint-disable @stylistic/max-len */ ```` --- ### no-blank-block-descriptions If tags are present, this rule will prevent empty lines in the block description. If no tags are present, this rule will prevent extra empty lines in the block description. ## Fixer Strips empty lines in block descriptions. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|(Block description)| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * * @param {number} x */ function functionWithClearName(x) {} // Message: There should be no blank lines in block descriptions followed by tags. /** * * */ function functionWithClearName() {} // Message: There should be no extra blank lines in block descriptions not followed by tags. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * Non-empty description * @param {number} x */ function functionWithClearName(x) {} /** * @param {number} x */ function functionWithClearName(x) {} /** * */ function functionWithClearName() {} /** */ function functionWithClearName() {} /** */ function functionWithClearName() {} /** Some desc. */ function functionWithClearName() {} /** @someTag */ function functionWithClearName() {} ```` --- # no-blank-blocks * [Fixer](#user-content-no-blank-blocks-fixer) * [`enableFixer`](#user-content-no-blank-blocks-fixer-enablefixer) * [Failing examples](#user-content-no-blank-blocks-failing-examples) * [Passing examples](#user-content-no-blank-blocks-passing-examples) Reports and optionally removes blocks with whitespace only. ## Fixer Auto-removes blank blocks with whitespace only. #### Options A single options object has the following properties. ### enableFixer Whether or not to auto-remove the blank block. Defaults to `false`. ||| |---|---| |Context|everywhere| |Tags|N/A| |Recommended|false| |Settings|| |Options|`enableFixer`| ## Failing examples The following patterns are considered problems: ````ts /** */ // "jsdoc/no-blank-blocks": ["error"|"warn", {"enableFixer":true}] // Message: No empty blocks /** */ // "jsdoc/no-blank-blocks": ["error"|"warn", {"enableFixer":true}] // Message: No empty blocks /** * */ // "jsdoc/no-blank-blocks": ["error"|"warn", {"enableFixer":true}] // Message: No empty blocks /** * * */ // "jsdoc/no-blank-blocks": ["error"|"warn", {"enableFixer":true}] // Message: No empty blocks /** * * */ // "jsdoc/no-blank-blocks": ["error"|"warn", {"enableFixer":false}] // Message: No empty blocks /** * * */ // Message: No empty blocks ```` ## Passing examples The following patterns are not considered problems: ````ts /** @tag */ /** * Text */ /** * @tag */ ```` --- # no-defaults * [Fixer](#user-content-no-defaults-fixer) * [Options](#user-content-no-defaults-options) * [`contexts`](#user-content-no-defaults-options-contexts) * [`noOptionalParamNames`](#user-content-no-defaults-options-nooptionalparamnames) * [Context and settings](#user-content-no-defaults-context-and-settings) * [Failing examples](#user-content-no-defaults-failing-examples) * [Passing examples](#user-content-no-defaults-passing-examples) This rule reports defaults being used on the relevant portion of `@param` or `@default`. It also optionally reports the presence of the square-bracketed optional arguments at all. The rule is intended to prevent the indication of defaults on tags where this would be redundant with ES6 default parameters (or for `@default`, where it would be redundant with the context to which the `@default` tag is attached). Unless your `@default` is on a function, you will need to set `contexts` to an appropriate context, including, if you wish, "any". ## Fixer Strips the default value. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### noOptionalParamNames Set this to `true` to report the presence of optional parameters. May be used if the project is insisting on optionality being indicated by the presence of ES6 default parameters (bearing in mind that such "defaults" are only applied when the supplied value is missing or `undefined` but not for `null` or other "falsey" values). ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`param`, `default`| |Aliases|`arg`, `argument`, `defaultvalue`| |Recommended|true| |Options|`contexts`, `noOptionalParamNames`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {number} [foo="7"] */ function quux (foo) { } // Message: Defaults are not permitted on @param. class Test { /** * @param {number} [foo="7"] */ quux (foo) { } } // Message: Defaults are not permitted on @param. /** * @param {number} [foo="7"] */ function quux (foo) { } // "jsdoc/no-defaults": ["error"|"warn", {"noOptionalParamNames":true}] // Message: Optional param names are not permitted on @param. /** * @arg {number} [foo="7"] */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} // Message: Defaults are not permitted on @arg. /** * @param {number} [foo="7"] */ function quux (foo) { } // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] // Message: Defaults are not permitted on @param. /** * @function * @param {number} [foo="7"] */ // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] // Message: Defaults are not permitted on @param. /** * @callback * @param {number} [foo="7"] */ // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] // Message: Defaults are not permitted on @param. /** * @default {} */ const a = {}; // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] // Message: Default values are not permitted on @default. /** * @defaultvalue {} */ const a = {}; // Settings: {"jsdoc":{"tagNamePreference":{"default":"defaultvalue"}}} // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] // Message: Default values are not permitted on @defaultvalue. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param foo */ function quux (foo) { } /** * @param {number} foo */ function quux (foo) { } /** * @param foo */ // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] /** * @function * @param {number} foo */ /** * @callback * @param {number} foo */ /** * @param {number} foo */ function quux (foo) { } // "jsdoc/no-defaults": ["error"|"warn", {"noOptionalParamNames":true}] /** * @default */ const a = {}; // "jsdoc/no-defaults": ["error"|"warn", {"contexts":["any"]}] ```` --- # no-missing-syntax * [Options](#user-content-no-missing-syntax-options) * [`contexts`](#user-content-no-missing-syntax-options-contexts) * [Context and settings](#user-content-no-missing-syntax-context-and-settings) * [Failing examples](#user-content-no-missing-syntax-failing-examples) * [Passing examples](#user-content-no-missing-syntax-passing-examples) This rule lets you report if certain always expected comment structures are missing. This (along with `no-restricted-syntax`) is a bit similar to Schematron for XML or jsontron for JSON--you can validate expectations of there being arbitrary structures. This differs from the rule of the same name in [`eslint-plugin-query`](https://github.com/brettz9/eslint-plugin-query) in that this rule always looks for a comment above a structure (whether or not you have a `comment` condition). This rule might be especially useful with [`overrides`](https://eslint.org/docs/user-guide/configuring/configuration-files#how-do-overrides-work) where you need only require tags and/or types within specific directories (e.g., to enforce that a plugins or locale directory always has a certain form of export and comment therefor). In addition to being generally useful for precision in requiring contexts, it is hoped that the ability to specify required tags on structures can be used for requiring `@type` or other types for a minimalist yet adequate specification of types which can be used to compile JavaScript+JSDoc (JJ) to WebAssembly (e.g., by converting it to TypeSscript and then using AssemblyScript to convert to WebAssembly). (It may be possible that one will need to require types with certain structures beyond function declarations and the like, as well as optionally requiring specification of number types.) Note that you can use selectors which make use of negators like `:not()` including with asterisk, e.g., `*:not(FunctionDeclaration)` to indicate types which are not adequate to satisfy a condition, e.g., `FunctionDeclaration:not(FunctionDeclaration[id.name="ignoreMe"])` would not report if there were only a function declaration of the name "ignoreMe" (though it would report by function declarations of other names). ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Use the `minimum` property (defaults to 1) to indicate how many are required for the rule to be reported. Use the `message` property to indicate the specific error to be shown when an error is reported for that context being found missing. You may use `{{context}}` and `{{comment}}` with such messages. Defaults to `"Syntax is required: {{context}}"`, or with a comment, to `"Syntax is required: {{context}} with {{comment}}"`. Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|None except those indicated by `contexts`| |Tags|Any if indicated by AST| |Recommended|false| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration"}]}] // Message: Syntax is required: FunctionDeclaration with JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Foo"]:nth-child(1)) /** * @implements {Bar|Foo} */ function quux () { } // Settings: {"jsdoc":{"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration"}]}} // Message: Syntax is required: FunctionDeclaration with JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Foo"]:nth-child(1)) /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration"}]}] // Message: Syntax is required: FunctionDeclaration with JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Foo"]:nth-child(1)) /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"any"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":":function"}]}] // Message: Syntax is required: :function with JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Foo"]:nth-child(1)) /** * @private * Object holding values of some custom enum */ const MY_ENUM = Object.freeze({ VAL_A: "myvala" } as const); // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[tag=/private|protected/])","context":":declaration","message":"Requiring private/protected tags here"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[tag=\"enum\"])","context":"any","message":"@enum required on declarations"}]}] // Message: @enum required on declarations /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration","message":"Problematically missing function syntax: `{{context}}` with `{{comment}}`."}]}] // Message: Problematically missing function syntax: `FunctionDeclaration` with `JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Foo"]:nth-child(1))`. /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":["FunctionDeclaration"]}] // Message: Syntax is required: FunctionDeclaration /** * @implements {Bar|Foo} */ function quux () { } // Message: Rule `no-missing-syntax` is missing a `contexts` option. /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration","minimum":2}]}] // Message: Syntax is required: FunctionDeclaration with JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Bar"]:nth-child(1)) /** * @param ab * @param cd */ // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Require names matching `/^opt_/i`."}]}] // Message: Require names matching `/^opt_/i`. /** * @param ab * @param cd */ // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","message":"Require names matching `/^opt_/i`."}]}] // Message: Require names matching `/^opt_/i`. /** * @param ab * @param cd */ function quux () {} // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Require names matching `/^opt_/i`."}]}] // Message: Require names matching `/^opt_/i`. /** * @implements {Bar|Foo} */ // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"context":"FunctionDeclaration"}]}] // Message: Syntax is required: FunctionDeclaration ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration"}]}] /** * @implements {Bar|Foo} */ function quux () { } /** * @implements {Bar|Foo} */ function bar () { } /** * @implements {Bar|Foo} */ function baz () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration","minimum":2}]}] /** * @param opt_a * @param opt_b */ // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Require names matching `/^opt_/i`."}]}] /** * @param opt_a * @param opt_b */ function quux () {} // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Require names matching `/^opt_/i`."}]}] /** * @param opt_a * @param opt_b */ function quux () {} // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","message":"Require names matching `/^opt_/i`."}]}] /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(2))","context":"FunctionDeclaration"}]}] /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-missing-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"any"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(2))","context":"FunctionDeclaration"}]}] ```` --- ### no-multi-asterisks Prevents use of multiple asterisks at the beginning of lines. Note that if you wish to prevent multiple asterisks at the very beginning of the JSDoc block, you should use `no-bad-blocks` (as that is not proper jsdoc and that rule is for catching blocks which only seem like jsdoc). ## Fixer Removes multiple asterisks on middle or end lines. ## Options A single options object has the following properties. ### allowWhitespace Set to `true` if you wish to allow asterisks after a space (as with Markdown): ```js /** * *bold* text */ ``` Defaults to `false`. ### preventAtEnd Prevent the likes of this: ```js /** * * **/ ``` Defaults to `true`. ### preventAtMiddleLines Prevent the likes of this: ```js /** * ** */ ``` Defaults to `true`. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|(Any)| |Recommended|true| |Settings|| |Options|`allowWhitespace`, `preventAtEnd`, `preventAtMiddleLines`| ## Failing examples The following patterns are considered problems: ````ts /** * ** */ // Message: Should be no multiple asterisks on middle lines. /** * ** */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtMiddleLines":true}] // Message: Should be no multiple asterisks on middle lines. /** * ** */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtEnd":false}] // Message: Should be no multiple asterisks on middle lines. /** * With a description * @tag {SomeType} and a tag with details ** */ // Message: Should be no multiple asterisks on middle lines. /** ** * */ // Message: Should be no multiple asterisks on middle lines. /** * Desc. * **/ // Message: Should be no multiple asterisks on end lines. /** * Desc. * **/ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtEnd":true}] // Message: Should be no multiple asterisks on end lines. /** * Desc. * abc * **/ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtEnd":true}] // Message: Should be no multiple asterisks on end lines. /** * Desc. * **/ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtMiddleLines":false}] // Message: Should be no multiple asterisks on end lines. /** Desc. **/ // Message: Should be no multiple asterisks on end lines. /** @someTag name desc. **/ // Message: Should be no multiple asterisks on end lines. /** abc * */ // Message: Should be no multiple asterisks on end lines. /** * Preserve user's whitespace when fixing (though one may also * use an align rule) * * */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtEnd":true}] // Message: Should be no multiple asterisks on end lines. /** * The method does 2 things: * * Thing 1 * * Thing 2 */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"allowWhitespace":false}] // Message: Should be no multiple asterisks on middle lines. /** * This muti-line comment contains some * *non-standard bold* syntax */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"allowWhitespace":false}] // Message: Should be no multiple asterisks on middle lines. /** Desc. **/ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"allowWhitespace":true}] // Message: Should be no multiple asterisks on end lines. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * * Desc. *** */ /** * Desc. *** * */ /** * Desc. * * sth */ /** ** * */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtMiddleLines":false}] /** * * **/ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"preventAtEnd":false}] /** * With a desc. * and *** */ /** * and *** * With a desc. */ /** * With a desc. * With a desc. * Desc. */ /** * With a description * @tag {SomeType} and a tag with details * */ /** abc */ function foo() { // } /** foo */ function foo(): void { // } /** @aTag abc */ function foo() { // } /** * **Bold** */ /** * Preserve user's bold statement when fixing. * * **Bold example:** Hi there. */ /** * The method does 2 things: * * Thing 1 * * Thing 2 */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"allowWhitespace":true}] /** * This muti-line comment contains some * *non-standard bold* syntax */ // "jsdoc/no-multi-asterisks": ["error"|"warn", {"allowWhitespace":true}] /** abc */ function foo() { // } // "jsdoc/no-multi-asterisks": ["error"|"warn", {"allowWhitespace":true}] ```` --- # no-restricted-syntax * [Options](#user-content-no-restricted-syntax-options) * [`contexts`](#user-content-no-restricted-syntax-options-contexts) * [Context and settings](#user-content-no-restricted-syntax-context-and-settings) * [Failing examples](#user-content-no-restricted-syntax-failing-examples) * [Passing examples](#user-content-no-restricted-syntax-passing-examples) Reports when certain comment structures are present. Note that this rule differs from ESLint's [no-restricted-syntax](https://eslint.org/docs/rules/no-restricted-syntax) rule in expecting values within a single options object's `contexts` property, and with the property `context` being used in place of `selector` (as well as allowing for `comment`). The format also differs from the format expected by [`eslint-plugin-query`](https://github.com/brettz9/eslint-plugin-query). Unlike those rules, this is specific to finding comments attached to structures, (whether or not you add a specific `comment` condition). Note that if your parser supports comment AST (as [jsdoc-eslint-parser](https://github.com/brettz9/jsdoc-eslint-parser) is designed to do), you can just use ESLint's rule. For an alternative to this rule, see the [Advanced](./docs/advanced.md#forbidding-structures) docs under creating your own rules and forbidding structures. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Use the `message` property to indicate the specific error to be shown when an error is reported for that context being found. Defaults to `"Syntax is restricted: {{context}}"`, or with a comment, to `"Syntax is restricted: {{context}} with {{comment}}"`. Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|None except those indicated by `contexts`| |Tags|Any if indicated by AST| |Recommended|false| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":["FunctionDeclaration"]}] // Message: Syntax is restricted: FunctionDeclaration /** * */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"context":"FunctionDeclaration","message":"Oops: `{{context}}`."}]}] // Message: Oops: `FunctionDeclaration`. /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration"}]}] // Message: Syntax is restricted: FunctionDeclaration with JsdocBlock[postDelimiter=""]:has(JsdocTypeUnion > JsdocTypeName[value="Bar"]:nth-child(1)) /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration","message":"The foo one: {{context}}."},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration","message":"The bar one: {{context}}."}]}] // Message: The bar one: FunctionDeclaration. /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"FunctionDeclaration","message":"The bar one: {{context}}."},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration","message":"The foo one: {{context}}."}]}] // Message: The bar one: FunctionDeclaration. /** * @implements {Bar|Foo} */ function quux () { } // Message: Rule `no-restricted-syntax` is missing a `contexts` option. /** * @implements {Bar|Foo} */ function quux () { } // Settings: {"jsdoc":{"contexts":["FunctionDeclaration"]}} // Message: Rule `no-restricted-syntax` is missing a `contexts` option. /** * @param opt_a * @param opt_b */ function a () {} // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"FunctionDeclaration","message":"Only allowing names not matching `/^opt_/i`."}]}] // Message: Only allowing names not matching `/^opt_/i`. /** * @param opt_a * @param opt_b */ function a () {} // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Only allowing names not matching `/^opt_/i`."}]}] // Message: Only allowing names not matching `/^opt_/i`. /** * @param opt_a * @param opt_b */ function a () {} // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","message":"Only allowing names not matching `/^opt_/i`."}]}] // Message: Only allowing names not matching `/^opt_/i`. /** * @param opt_a * @param opt_b */ function a () {} // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/not-this/])","context":"any","message":"Only allowing names not matching `/^not-this/i`."},{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Only allowing names not matching `/^opt_/i`."}]}] // Message: Only allowing names not matching `/^opt_/i`. /** * @param opt_a * @param opt_b */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Only allowing names not matching `/^opt_/i`."}]}] // Message: Only allowing names not matching `/^opt_/i`. /** * @enum {String} * Object holding values of some custom enum */ const MY_ENUM = Object.freeze({ VAL_A: "myvala" } as const); // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag ~ JsdocTag[tag=/private|protected/])","context":"any","message":"Access modifier tags must come first"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[tag=\"enum\"])","context":":declaration","message":"@enum not allowed on declarations"}]}] // Message: @enum not allowed on declarations /** @type {React.FunctionComponent<{ children: React.ReactNode }>}*/ const MyComponent = ({ children }) => { return children; } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=\"type\"]:has([value=/FunctionComponent/]))","context":"any","message":"The `FunctionComponent` type is not allowed. Please use `FC` instead."}]}] // Message: The `FunctionComponent` type is not allowed. Please use `FC` instead. /** Some text and more */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[descriptionStartLine=0][descriptionEndLine=0]","context":"any","message":"Requiring descriptive text on 0th line only"}]}] // Message: Requiring descriptive text on 0th line only /** Some text and * more */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[descriptionStartLine=0][hasPreterminalDescription=0]","context":"any","message":"Requiring descriptive text on 0th line and no preterminal description"}]}] // Message: Requiring descriptive text on 0th line and no preterminal description /** Some text * @param sth Param text followed by no newline */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[descriptionStartLine=0][hasPreterminalTagDescription=1]","context":"any","message":"Requiring descriptive text on 0th line but no preterminal description"}]}] // Message: Requiring descriptive text on 0th line but no preterminal description /** * */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=see]))","context":"any","message":"@see required on each block"}]}] // Message: @see required on each block /** * @type {{a: string}} */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type!=JsdocTypeStringValue][parsedType.type!=JsdocTypeNumber][parsedType.type!=JsdocTypeName])","context":"any","message":"@type should be limited to numeric or string literals and names"},{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type=JsdocTypeName]:not(*[parsedType.value=/^(true|false|null|undefined|boolean|number|string)$/]))","context":"any","message":"@type names should only be recognized primitive types or literals"}]}] // Message: @type should be limited to numeric or string literals and names /** * @type {abc} */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type!=JsdocTypeStringValue][parsedType.type!=JsdocTypeNumber][parsedType.type!=JsdocTypeName])","context":"any","message":"@type should be limited to numeric or string literals and names"},{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type=JsdocTypeName]:not(*[parsedType.value=/^(true|false|null|undefined|boolean|number|string)$/]))","context":"any","message":"@type names should only be recognized primitive types or literals"}]}] // Message: @type names should only be recognized primitive types or literals /** * */ function test(): string { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]))","context":"FunctionDeclaration[returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/]","message":"Functions with non-void return types must have a @returns tag"}]}] // Message: Functions with non-void return types must have a @returns tag /** * */ let test = (): string => { }; // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]))","context":"ArrowFunctionExpression[returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/]","message":"Functions with non-void return types must have a @returns tag"}]}] // Message: Functions with non-void return types must have a @returns tag /** * @returns */ let test: () => string; // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]:has(JsdocDescriptionLine)))","context":"VariableDeclaration:has(*[typeAnnotation.typeAnnotation.type=/TSFunctionType/][typeAnnotation.typeAnnotation.returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/])","message":"FunctionType's with non-void return types must have a @returns tag with a description"}]}] // Message: FunctionType's with non-void return types must have a @returns tag with a description /** * */ class Test { abstract Test(): string; } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]))","context":"TSEmptyBodyFunctionExpression[returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/]","message":"methods with non-void return types must have a @returns tag"}]}] // Message: methods with non-void return types must have a @returns tag /** * This has an inline {@link http://example.com} */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocInlineTag)","context":"FunctionDeclaration"}]}] // Message: Syntax is restricted: FunctionDeclaration with JsdocBlock:has(JsdocInlineTag) /** * @see This has an inline {@link http://example.com} */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag:has(JsdocInlineTag[format=\"plain\"]))","context":"FunctionDeclaration"}]}] // Message: Syntax is restricted: FunctionDeclaration with JsdocBlock:has(JsdocTag:has(JsdocInlineTag[format="plain"])) ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":["FunctionExpression"]}] /** * @implements {Bar|Foo} */ function quux () { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Foo\"]:nth-child(1))","context":"FunctionDeclaration"}]}] /** * @param ab * @param cd */ function a () {} // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Only allowing names not matching `/^opt_/i`."}]}] /** * @param ab * @param cd */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","context":"any","message":"Only allowing names not matching `/^opt_/i`."}]}] /** * @param ab * @param cd */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[name=/opt_/])","message":"Only allowing names not matching `/^opt_/i`."}]}] /** * @enum {String} * Object holding values of some custom enum */ const MY_ENUM = Object.freeze({ VAL_A: "myvala" } as const); // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag ~ JsdocTag[tag=/private|protected/])","context":"any","message":"Access modifier tags must come first"},{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[tag=\"enum\"])","context":":declaration:not(TSEnumDeclaration):not(:has(ObjectExpression)), :function","message":"@enum is only allowed on potential enum types"}]}] /** * @param {(...args: any[]) => any} fn * @returns {(...args: any[]) => any} */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=\"type\"]:has([value=/FunctionComponent/]))","context":"any","message":"The `FunctionComponent` type is not allowed. Please use `FC` instead."}]}] /** Does something very important. */ function foo(): string; // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[endLine=0][description!=/^\\S[\\s\\S]*\\S\\s$/]"}]}] /** Some text and more */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[descriptionStartLine=0][descriptionEndLine=1]","context":"any","message":"Requiring descriptive text on 0th line and no final newline"}]}] /** Some text and * more */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[descriptionStartLine=0][hasPreterminalDescription=0]","context":"any","message":"Requiring descriptive text on 0th line and no preterminal description"}]}] /** Some text * @param sth Param text followed by newline */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[descriptionStartLine=0][hasPreterminalTagDescription=1]","context":"any","message":"Requiring descriptive text on 0th line but no preterminal description"}]}] /** * @type {123} */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type!=JsdocTypeStringValue][parsedType.type!=JsdocTypeNumber][parsedType.type!=JsdocTypeName])","context":"any","message":"@type should be limited to numeric or string literals and names"},{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type=JsdocTypeName]:not(*[parsedType.value=/^(true|false|null|undefined|boolean|number|string)$/]))","context":"any","message":"@type names should only be recognized primitive types or literals"}]}] /** * @type {boolean} */ // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type!=JsdocTypeStringValue][parsedType.type!=JsdocTypeNumber][parsedType.type!=JsdocTypeName])","context":"any","message":"@type should be limited to numeric or string literals and names"},{"comment":"JsdocBlock:has(JsdocTag[tag=type][parsedType.type=JsdocTypeName]:not(*[parsedType.value=/^(true|false|null|undefined|boolean|number|string)$/]))","context":"any","message":"@type names should only be recognized primitive types or literals"}]}] /** * */ function test(): void { } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]))","context":"FunctionDeclaration[returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/]","message":"Functions with return types must have a @returns tag"}]}] /** * */ let test = (): undefined => { }; // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]))","context":"ArrowFunctionExpression[returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/]","message":"Functions with non-void return types must have a @returns tag"}]}] /** * @returns A description */ let test: () => string; // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]:has(JsdocDescriptionLine)))","context":"VariableDeclaration:has(*[typeAnnotation.typeAnnotation.type=/TSFunctionType/])","message":"FunctionType's with non-void return types must have a @returns tag"}]}] /** * */ class Test { abstract Test(): void; } // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(*:has(JsdocTag[tag=/returns/]))","context":"TSEmptyBodyFunctionExpression[returnType.typeAnnotation.type!=/TSVoidKeyword|TSUndefinedKeyword/]","message":"methods with non-void return types must have a @returns tag"}]}] /** * @private */ function quux () {} // "jsdoc/no-restricted-syntax": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:not(JsdocBlock:has(JsdocTag[tag=/private|protected|public/]))","context":"any","message":"Access modifier tags must be present"}]}] ```` --- # no-types * [Fixer](#user-content-no-types-fixer) * [Options](#user-content-no-types-options) * [`contexts`](#user-content-no-types-options-contexts) * [Context and settings](#user-content-no-types-context-and-settings) * [Failing examples](#user-content-no-types-failing-examples) * [Passing examples](#user-content-no-types-passing-examples) This rule reports types being used on `@param` or `@returns`. The rule is intended to prevent the indication of types on tags where the type information would be redundant with TypeScript. When `contexts` are supplied, will also strip `@property` when on a `ClassDeclaration`. ## Fixer Strips any types that are found. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`, `TSDeclareFunction`, `TSMethodSignature`, `ClassDeclaration`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`param`, `returns`| |Aliases|`arg`, `argument`, `return`| |Recommended|false| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {number} foo */ function quux (foo) { } // Message: Types are not permitted on @param. class quux { /** * @param {number} foo */ bar (foo) { } } // Message: Types are not permitted on @param. /** * @param {number} foo */ function quux (foo) { } // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] // Message: Types are not permitted on @param. class quux { /** * @param {number} foo */ quux (foo) { } } // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] // Message: Types are not permitted on @param. /** * @function * @param {number} foo */ // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] // Message: Types are not permitted on @param. /** * @callback * @param {number} foo */ // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] // Message: Types are not permitted on @param. /** * @returns {number} */ function quux () { } // Message: Types are not permitted on @returns. /** * Beep * Boop * * @returns {number} */ function quux () { } // Message: Types are not permitted on @returns. export interface B { /** * @param {string} paramA */ methodB(paramB: string): void } // Message: Types are not permitted on @param. /** * @class * @property {object} x */ class Example { x: number; } // Message: Types are not permitted on @property in the supplied context. /** * Returns a Promise... * * @param {number} ms - The number of ... */ const sleep = (ms: number): Promise => {}; // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] // Message: Types are not permitted on @param. /** * Returns a Promise... * * @param {number} ms - The number of ... */ export const sleep = (ms: number): Promise => {}; // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] // Message: Types are not permitted on @param. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param foo */ function quux (foo) { } /** * @param foo */ // "jsdoc/no-types": ["error"|"warn", {"contexts":["any"]}] /** * @function * @param {number} foo */ /** * @callback * @param {number} foo */ /*** Oops that's too many asterisks by accident **/ function a () {} ```` --- # no-undefined-types * [Options](#user-content-no-undefined-types-options) * [`checkUsedTypedefs`](#user-content-no-undefined-types-options-checkusedtypedefs) * [`definedTypes`](#user-content-no-undefined-types-options-definedtypes) * [`disableReporting`](#user-content-no-undefined-types-options-disablereporting) * [`markVariablesAsUsed`](#user-content-no-undefined-types-options-markvariablesasused) * [Context and settings](#user-content-no-undefined-types-context-and-settings) * [Failing examples](#user-content-no-undefined-types-failing-examples) * [Passing examples](#user-content-no-undefined-types-passing-examples) Checks that types in JSDoc comments are defined. This can be used to check unimported types. When enabling this rule, types in JSDoc comments will resolve as used variables, i.e. will not be marked as unused by `no-unused-vars`. In addition to considering globals found in code (or in ESLint-indicated `globals`) as defined, the following tags will also be checked for name(path) definitions to also serve as a potential "type" for checking the tag types in the table below: `@callback`, `@class` (or `@constructor`), `@constant` (or `@const`), `@event`, `@external` (or `@host`), `@function` (or `@func` or `@method`), `@interface`, `@member` (or `@var`), `@mixin`, `@name`, `@namespace`, `@template` (for "closure" or "typescript" `settings.jsdoc.mode` only), `@import` (for TypeScript), `@typedef`. The following tags will also be checked but only when the mode is `closure`: `@package`, `@private`, `@protected`, `@public`, `@static` The following types are always considered defined. - `null`, `undefined`, `void`, `string`, `boolean`, `object`, `function`, `symbol` - `number`, `bigint`, `NaN`, `Infinity` - `any`, `*`, `never`, `unknown`, `const` - `this`, `true`, `false` - `Array`, `Object`, `RegExp`, `Date`, `Function` Note that preferred types indicated within `settings.jsdoc.preferredTypes` will also be assumed to be defined. Also note that if there is an error [parsing](https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser) types for a tag, the function will silently ignore that tag, leaving it to the `valid-types` rule to report parsing errors. If you define your own tags, you can use `settings.jsdoc.structuredTags` to indicate that a tag's `name` is "name-defining" or "namepath-defining" (and should prevent reporting on use of that namepath elsewhere) and/or that a tag's `type` is `false` (and should not be checked for types). If the `type` is an array, that array's items will be considered as defined for the purposes of that tag. ## Options A single options object has the following properties. ### checkUsedTypedefs Whether to check typedefs for use within the file ### definedTypes This array can be populated to indicate other types which are automatically considered as defined (in addition to globals, etc.). Defaults to an empty array. ### disableReporting Whether to disable reporting of errors. Defaults to `false`. This may be set to `true` in order to take advantage of only marking defined variables as used or checking used typedefs. ### markVariablesAsUsed Whether to mark variables as used for the purposes of the `no-unused-vars` rule when they are not found to be undefined. Defaults to `true`. May be set to `false` to enforce a practice of not importing types unless used in code. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`augments`, `class`, `constant`, `enum`, `implements`, `member`, `module`, `namespace`, `param`, `property`, `returns`, `throws`, `type`, `typedef`, `yields`| |Aliases|`constructor`, `const`, `extends`, `var`, `arg`, `argument`, `prop`, `return`, `exception`, `yield`| |Closure-only|`package`, `private`, `protected`, `public`, `static`| |Recommended|true| |Options|`checkUsedTypedefs`, `definedTypes`, `disableReporting`, `markVariablesAsUsed`| |Settings|`preferredTypes`, `mode`, `structuredTags`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {HerType} baz - Foo. */ function quux(foo, bar, baz) { } // Settings: {"jsdoc":{"preferredTypes":{"HerType":1000}}} // Message: Invalid `settings.jsdoc.preferredTypes`. Values must be falsy, a string, or an object. /** * @param {HerType} baz - Foo. */ function quux(foo, bar, baz) { } // Settings: {"jsdoc":{"preferredTypes":{"HerType":false}}} // Message: The type 'HerType' is undefined. /** * @param {strnig} foo - Bar. */ function quux(foo) { } // Message: The type 'strnig' is undefined. /** * @param {MyType} foo - Bar. * @param {HisType} bar - Foo. */ function quux(foo, bar) { } // "jsdoc/no-undefined-types": ["error"|"warn", {"definedTypes":["MyType"]}] // Message: The type 'HisType' is undefined. /** * @param {MyType} foo - Bar. * @param {HisType} bar - Foo. * @param {HerType} baz - Foo. */ function quux(foo, bar, baz) { } // Settings: {"jsdoc":{"preferredTypes":{"hertype":{"replacement":"HerType"}}}} // "jsdoc/no-undefined-types": ["error"|"warn", {"definedTypes":["MyType"]}] // Message: The type 'HisType' is undefined. /** * @param {MyType} foo - Bar. * @param {HisType} bar - Foo. * @param {HerType} baz - Foo. */ function quux(foo, bar, baz) { } // Settings: {"jsdoc":{"preferredTypes":{"hertype":{"replacement":false},"histype":"HisType"}}} // "jsdoc/no-undefined-types": ["error"|"warn", {"definedTypes":["MyType"]}] // Message: The type 'HerType' is undefined. /** * @template TEMPLATE_TYPE * @param {WRONG_TEMPLATE_TYPE} bar */ function foo (bar) { }; // Settings: {"jsdoc":{"mode":"closure"}} // Message: The type 'WRONG_TEMPLATE_TYPE' is undefined. class Foo { /** * @return {TEMPLATE_TYPE} */ bar () { } } // Message: The type 'TEMPLATE_TYPE' is undefined. class Foo { /** * @return {TEMPLATE_TYPE} */ invalidTemplateReference () { } } /** * @template TEMPLATE_TYPE */ class Bar { /** * @return {TEMPLATE_TYPE} */ validTemplateReference () { } } // Settings: {"jsdoc":{"mode":"typescript"}} // Message: The type 'TEMPLATE_TYPE' is undefined. /** * @type {strnig} */ var quux = { }; // Message: The type 'strnig' is undefined. /** * @template TEMPLATE_TYPE_A, TEMPLATE_TYPE_B */ class Foo { /** * @param {TEMPLATE_TYPE_A} baz * @return {TEMPLATE_TYPE_B} */ bar (baz) { } } // Settings: {"jsdoc":{"mode":"jsdoc"}} // Message: The type 'TEMPLATE_TYPE_A' is undefined. /** * @param {...VAR_TYPE} varargs */ function quux (varargs) { } // Message: The type 'VAR_TYPE' is undefined. /** * @this {Navigator} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: The type 'Navigator' is undefined. /** * @export {SomeType} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: The type 'SomeType' is undefined. /** * @aCustomTag {SomeType} */ function quux () {} // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":true}}}} // Message: The type 'SomeType' is undefined. /** * @aCustomTag {SomeType} */ function quux () {} // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":["aType","anotherType"]}}}} // Message: The type 'SomeType' is undefined. /** * @namepathReferencing SomeType */ /** * @type {SomeType} */ // Settings: {"jsdoc":{"structuredTags":{"namepathReferencing":{"name":"namepath-referencing"}}}} // Message: The type 'SomeType' is undefined. /** * @template abc TEMPLATE_TYPE * @param {TEMPLATE_TYPE} bar */ function foo (bar) { }; // Settings: {"jsdoc":{"mode":"closure"}} // Message: The type 'TEMPLATE_TYPE' is undefined. /** * @suppress {visibility} */ function foo () { } // Settings: {"jsdoc":{"mode":"jsdoc"}} // Message: The type 'visibility' is undefined. /** * @typedef Todo * @property description * @property otherStuff */ /** * @type {Omit} */ const a = new Todo(); // Settings: {"jsdoc":{"mode":"jsdoc"}} // Message: The type 'Omit' is undefined. /** * Message with {@link NotKnown} */ // Message: The type 'NotKnown' is undefined. /** * Message with * a link that is {@link NotKnown} */ // Message: The type 'NotKnown' is undefined. /** * @abc * @someTag Message with * a link that is {@link NotKnown} */ // Message: The type 'NotKnown' is undefined. /** * This is a {@namepathOrURLReferencer SomeType}. */ // Settings: {"jsdoc":{"structuredTags":{"namepathOrURLReferencer":{"name":"namepath-or-url-referencing"}}}} // Message: The type 'SomeType' is undefined. /** * @import BadImportIgnoredByThisRule */ /** * @import LinterDef, { Sth as Something, Another as Another2 } from "eslint" */ /** * @import { Linter } from "eslint" */ /** * @import LinterDefault from "eslint" */ /** * @import {Linter as Lintee} from "eslint" */ /** * @import * as Linters from "eslint" */ /** * @type {BadImportIgnoredByThisRule} */ /** * @type {Sth} */ /** * @type {Another} */ // Message: The type 'BadImportIgnoredByThisRule' is undefined. class Filler { /** * {@link Filler.methodTwo} non-existent * {@link Filler.nonStaticMethodTwo} non-existent too * {@link Filler.methodThree} existent * @returns {string} A string indicating the method's purpose. */ methodOne() { return 'Method Four'; } methodThree() {} } // Message: The type 'Filler.methodTwo' is undefined. /** @typedef {string} SomeType */ /** @typedef {number} AnotherType */ /** @type {AnotherType} */ // "jsdoc/no-undefined-types": ["error"|"warn", {"checkUsedTypedefs":true}] // Message: This typedef was not used within the file /** @typedef {'cwd'} */ let MyOwnType1 /** * @param {`${MyOwnType1}-${string}`} tagName * @param {CustomElementConstructor} component */ let defineCustomElement = (tagName, component) => { customElements.define(tagName, component) } /** @typedef {string} */ let MyOwnType2 /** * @param {(element: MyOwnType2) => T} callback * @returns {void} */ let getValue = (callback) => { callback(`hello`) } // Message: The type 'CustomElementConstructor' is undefined. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {string} foo - Bar. */ function quux(foo) { } /** * @param {Promise} foo - Bar. */ function quux(foo) { } class MyClass {} /** * @param {MyClass} foo - Bar. */ function quux(foo) { console.log(foo); } quux(0); const MyType = require('my-library').MyType; /** * @param {MyType} foo - Bar. */ function quux(foo) { } const MyType = require('my-library').MyType; /** * @param {MyType} foo - Bar. */ function quux(foo) { } import {MyType} from 'my-library'; /** * @param {MyType} foo - Bar. * @param {object} foo * @param {Array} baz */ function quux(foo, bar, baz) { } /*globals MyType*/ /** * @param {MyType} foo - Bar. * @param {HisType} bar - Foo. */ function quux(foo, bar) { } /** * @typedef {object} hello * @property {string} a - a. */ /** * @param {hello} foo */ function quux(foo) { } /** * @param {Array"},"histype":"HisType.<>"}}} // "jsdoc/no-undefined-types": ["error"|"warn", {"definedTypes":["MyType"]}] /** * @template TEMPLATE_TYPE * @param {TEMPLATE_TYPE} bar * @return {TEMPLATE_TYPE} */ function foo (bar) { }; // Settings: {"jsdoc":{"mode":"closure"}} /** * @template TEMPLATE_TYPE */ class Foo { /** * @return {TEMPLATE_TYPE} */ bar () { } } // Settings: {"jsdoc":{"mode":"closure"}} /** * @template TEMPLATE_TYPE */ class Foo { /** * @return {TEMPLATE_TYPE} */ bar () {} /** * @return {TEMPLATE_TYPE} */ baz () {} } // Settings: {"jsdoc":{"mode":"closure"}} /** * @template TEMPLATE_TYPE_A, TEMPLATE_TYPE_B */ class Foo { /** * @param {TEMPLATE_TYPE_A} baz * @return {TEMPLATE_TYPE_B} */ bar (baz) { } } // Settings: {"jsdoc":{"mode":"closure"}} /** * @template TEMPLATE_TYPE_A, TEMPLATE_TYPE_B - Some description */ class Foo { /** * @param {TEMPLATE_TYPE_A} baz * @return {TEMPLATE_TYPE_B} */ bar (baz) { } } // Settings: {"jsdoc":{"mode":"closure"}} /****/ /* */ /*** */ /** * */ function quux () { } /** * @typedef {object} BaseObject */ /** * Run callback when hooked method is called. * * @template {BaseObject} T * @param {T} obj - object whose method should be hooked. * @param {string} method - method which should be hooked. * @param {(sender: T) => void} callback - callback which should * be called when the hooked method was invoked. */ function registerEvent(obj, method, callback) { } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @param {...} varargs */ function quux (varargs) { } /** * @param {...number} varargs */ function quux (varargs) { } class Navigator {} /** * @this {Navigator} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} class SomeType {} /** * @export {SomeType} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @template T * @param {T} arg */ function example(arg) { /** @param {T} */ function inner(x) { } } // Settings: {"jsdoc":{"mode":"closure"}} const init = () => { /** * Makes request * @returns {Promise} */ function request() { return Promise.resolve('success'); } }; /** Gets a Promise resolved with a given value. * * @template ValueType * @param {ValueType} value Value to resolve. * @returns {Promise} Promise resolved with value. */ exports.resolve1 = function resolve1(value) { return Promise.resolve(value); }; // Settings: {"jsdoc":{"mode":"typescript"}} /** * A function returning the same type as its argument. * * @template ValueType * @typedef {ValueType} ValueFunc */ // Settings: {"jsdoc":{"mode":"typescript"}} /** * @aCustomTag {SomeType} */ function quux () {} // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":false}}}} /** * @aCustomTag {SomeType} */ function quux () {} // Settings: {"jsdoc":{"structuredTags":{"aCustomTag":{"type":["aType","SomeType"]}}}} /** * @namepathDefiner SomeType */ /** * @type {SomeType} */ // Settings: {"jsdoc":{"structuredTags":{"namepathDefiner":{"name":"namepath-defining"}}}} class Test { /** * Method. * * @returns {this} Return description. */ method (): this { return this; } } /** * Bad types ignored here and handled instead by `valid-types`. * @param {string(} foo - Bar. */ function quux(foo) { } /** * @template T * @param {T} arg * @returns {[T]} */ function genericFunctionExample(arg) { const result = /** @type {[T]} */ (new Array()); result[0] = arg; return result; } // Settings: {"jsdoc":{"mode":"closure"}} /** @typedef QDigestNode */ class A { /** * @template {object} T * @param {(node: QDigestNode) => T} callback * @returns {T[]} */ map(callback) { /** @type {T[]} */ let vals; return vals; } } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @template T * @param {T} arg */ function example(arg) { /** @param {T} */ function inner(x) { } } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @suppress {visibility} */ function foo () { } // Settings: {"jsdoc":{"mode":"closure"}} /** * @template T */ export class Foo { // cast to T getType() { const x = "hello"; const y = /** @type {T} */ (x); return y; } } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @type {const} */ const a = 'string'; /** * @typedef Todo * @property description * @property otherStuff */ /** * @type {Omit} */ const a = new Todo(); // Settings: {"jsdoc":{"mode":"typescript"}} /** * @template A, [B=SomeDefault] */ class Foo { /** * @param {A} baz * @return {B} */ bar (baz) { } } // Settings: {"jsdoc":{"mode":"typescript"}} import {MyType} from 'my-library'; /** * @param {MyType} foo - Bar. * @param {AnUndefinedType} bar */ function quux(foo, bar) { } // "jsdoc/no-undefined-types": ["error"|"warn", {"disableReporting":true}] class MyClass {} class AnotherClass {} /** * A description mentioning {@link MyClass} and {@link AnotherClass | another class} and a URL via [this link]{@link https://www.example.com}. */ function quux(foo) { console.log(foo); } quux(0); class MyClass {} class AnotherClass {} /** * @see A tag mentioning {@link MyClass} and {@link AnotherClass | another class} and a URL via [this link]{@link https://www.example.com}. */ function quux(foo) { console.log(foo); } quux(0); function quux() { const foo = 1; /** {@link foo} */ const bar = foo; console.log(bar); } quux(); /** * @import BadImportIgnoredByThisRule */ /** * @import LinterDef, { Sth as Something, Another as Another2 } from "eslint" */ /** * @import LinterDef2, * as LinterDef3 from "eslint" */ /** * @import { Linter } from "eslint" */ /** * @import LinterDefault from "eslint" */ /** * @import {Linter as Lintee} from "eslint" */ /** * @import * as Linters from "eslint" */ /** * @type {LinterDef} */ /** * @type {LinterDef2} */ /** * @type {LinterDef3} */ /** * @type {Something} */ /** * @type {Another2} */ /** * @type {Linter} */ /** * @type {LinterDefault} */ /** * @type {Lintee} */ /** * @type {Linters} */ class Filler { static methodOne () { return 'Method One'; } nonStaticMethodTwo (param) { return `Method Two received: ${param}`; } /** * {@link methodOne} shouldn't report eslint error * {@link nonStaticMethodTwo} also shouldn't report eslint error * @returns {number} A number representing the answer to everything. */ static methodThree () { return 42; } /** * {@link Filler.methodOne} doesn't report eslint error * {@link Filler.nonStaticMethodTwo} also doesn't report eslint error * @returns {string} A string indicating the method's purpose. */ methodFour() { return 'Method Four'; } } class Foo { foo = "foo"; /** * Something related to {@link foo} * @returns {string} Something awesome */ bar() { return "bar"; } } /* globals SomeGlobal, AnotherGlobal */ import * as Ably from "ably" import Testing, { another as Another, stillMore as StillMore } from "testing" export class Code { /** @type {Ably.Realtime} */ static #client /** @type {Testing.SomeMethod} */ static #test /** @type {Another.AnotherMethod} */ static #test2 /** @type {StillMore.AnotherMethod} */ static #test3 /** @type {AnotherGlobal.AnotherMethod} */ static #test4 /** @type {AGlobal.AnotherMethod} */ static #test5 } import jsdoc from "eslint-plugin-jsdoc"; /** * @import { Linter } from "eslint" */ /** * @type {Linter.Config} */ export default [ { plugins: { jsdoc }, rules: { "jsdoc/no-undefined-types": "error" } } ]; /** * @typedef {object} Abc * @property {string} def Some string */ /** * @type {Abc['def']} */ export const a = 'someString'; export interface SomeInterface { someProp: unknown; } /** * {@link SomeInterface.someProp} * @returns something */ class SomeClass { someMethod () {} } /** * {@link SomeClass.someMethod} * @returns something */ /** * The internationalized collator object that will be used. * Intl.Collator(null, {numeric: true, sensitivity: 'base'}) is used by default;. * * @member {Intl.Collator} */ const otherFile = require('./other-file'); /** * A function * @param {otherFile.MyType} a */ function f(a) {} /**@typedef {import('restify').Request} Request */ /**@typedef {import('./types').helperError} helperError */ /** * @param {Request} b * @param {helperError} c */ function a (b, c) {} /** @typedef {string} SomeType */ /** @type {SomeType} */ // "jsdoc/no-undefined-types": ["error"|"warn", {"checkUsedTypedefs":true}] /** @typedef {string} MyOwnType */ /** * @template T * @param {(element: MyOwnType) => T} cb * @returns {void} */ const getValue = () => {}; /** @typedef {string} MyOwnType */ /** @typedef {new () => void} CustomElementConstructor */ /** * @param {`${MyOwnType}-${string}`} tagName * @param {CustomElementConstructor} component */ const defineCustomElement = (tagName, component) => { }; class Storage { /** @type {globalThis.localStorage} */ #storage } /** * La liste des sévérités. * * @type {Object} */ const Severities = { FATAL: 1, ERROR: 2, WARN: 3, INFO: 4, }; /** * @typedef {Severities[keyof Severities]} Severity Le type des sévérités. */ export default Severities; /** * @template {unknown} T * @param {unknown} value * @param {...T} validValues * @returns {value is T} */ const checkIsOnOf = (value, ...validValues) => { return validValues.includes(value); }; ```` --- # prefer-import-tag Prefer `@import` tags to inline `import()` statements. ## Fixer Creates `@import` tags if an already existing matching `@typedef` or `@import` is not found. ## Options A single options object has the following properties. ### enableFixer Whether or not to enable the fixer to add `@import` tags. ### exemptTypedefs Whether to allow `import()` statements within `@typedef` ### outputType What kind of `@import` to generate when no matching `@typedef` or `@import` is found ||| |---|---| |Context|everywhere| |Tags|`augments`, `class`, `constant`, `enum`, `implements`, `member`, `module`, `namespace`, `param`, `property`, `returns`, `throws`, `type`, `typedef`, `yields`| |Aliases|`constructor`, `const`, `extends`, `var`, `arg`, `argument`, `prop`, `return`, `exception`, `yield`| |Closure-only|`package`, `private`, `protected`, `public`, `static`| |Recommended|false| |Settings|`mode`| |Options|`enableFixer`, `exemptTypedefs`, `outputType`| ## Failing examples The following patterns are considered problems: ````ts /** * @type {import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').Rule.Node} */ // Settings: {"jsdoc":{"mode":"permissive"}} // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"outputType":"named-import"}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"outputType":"namespaced-import"}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').Rule['Node']} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"outputType":"named-import"}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').Rule['Node']} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"outputType":"namespaced-import"}] // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint2').Rule.Node} RuleNode */ /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":false}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint')} */ // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint')} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').default} */ // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').default} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false}] // Message: Inline `import()` found; prefer `@import` /** @import * as eslint2 from 'eslint'; */ /** * @type {import('eslint')} */ // Message: Inline `import()` found; prefer `@import` /** @import eslint2 from 'eslint'; */ /** * @type {import('eslint').default} */ // Message: Inline `import()` found; prefer `@import` /** @import eslint2 from 'eslint'; */ /** * @type {import('eslint').default} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false}] // Message: Inline `import()` found; prefer `@import` /** @import {Rule} from 'eslint' */ /** * @type {import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** @import {Rule} from 'eslint' */ /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false}] // Message: Inline `import()` found; prefer `@import` /** @import * as eslint2 from 'eslint' */ /** * @type {import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** @import * as eslint2 from 'eslint' */ /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false}] // Message: Inline `import()` found; prefer `@import` /** @import LinterDef2, * as LinterDef3 from "eslint" */ /** * @type {import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** * @import LinterDef2, * as LinterDef3 from "eslint" */ /** * @type {import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** * @import LinterDef2, * * as LinterDef3 from "eslint" */ /** * @type {import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** * @import { * ESLint * } from "eslint" */ /** * @type {import('eslint').ESLint.Node} */ // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint').Rule} Rule */ /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @typedef {import('eslint').Rule} Rule */ /** * @type {import('eslint').Rule.Node.Abc.Def} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @typedef {import('eslint').Rule} Rule */ /** * @type {import('eslint').Rule.Node.Abc['Def']} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @typedef {import('eslint').Rule.Node} RuleNode */ /** * @type {import('eslint').Rule.Node} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** * @type {number|import('eslint').Rule.Node} */ // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint').Rule.Node} Rule */ /** * @type {import('eslint').Rule} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint').Rule.Node} Rule */ /** * @type {import('eslint').Rule.Abc} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint').Rule} Rule */ /** * @type {import('eslint').Rule.Node.Abc.Rule} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @typedef {import('eslint').Rule} Rule */ /** * @type {import('eslint').Rule.Node.Abc.Rule} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"enableFixer":false,"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @typedef {import('eslint').Rule.Rule} Rule */ /** * @type {import('eslint').Abc.Rule} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; prefer `@import` /** * @type {import('eslint').anchors[keyof DataMap.anchors]} */ // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint').Rule[keyof import('eslint').Rule]} Rule */ /** * @type {import('eslint').Abc.Rule} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; prefer `@import` /** @typedef {import('eslint').Rule[keyof import('eslint').Rule]} Rule */ /** * @type {import('eslint').Rule[keyof import('eslint').Rule]} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @typedef {import('eslint').Rule} Rule */ /** * @type {import('eslint').Rule[keyof import('eslint').Rule]} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] // Message: Inline `import()` found; using `@typedef` /** @type {import('foo')} */ let foo; // Message: Inline `import()` found; prefer `@import` /** @type {import('foo')} */ let foo; // Message: Inline `import()` found; prefer `@import` /** @type {import('foo').bar} */ let foo; // Message: Inline `import()` found; prefer `@import` /** @type {import('foo').bar} */ let foo; // "jsdoc/prefer-import-tag": ["error"|"warn", {"outputType":"named-import"}] // Message: Inline `import()` found; prefer `@import` /** @type {import('foo').default} */ let foo; // Message: Inline `import()` found; prefer `@import` /** @type { import('@typescript-eslint/utils').TSESLint.FlatConfig.Config['rules'] } */ // Message: Inline `import()` found; prefer `@import` /** @type { import('node:zlib').createGzip } */ // Message: Inline `import()` found; prefer `@import` /** @type { import('./lib/someFile.js').someImport } */ // Message: Inline `import()` found; prefer `@import` ```` ## Passing examples The following patterns are not considered problems: ````ts /** @typedef {import('eslint').Rule.Node} RuleNode */ /** * @type {RuleNode} */ // "jsdoc/prefer-import-tag": ["error"|"warn", {"exemptTypedefs":true}] /** @import {Rule} from 'eslint' */ /** * @type {Rule.Node} */ /** @import * as eslint from 'eslint' */ /** * @type {eslint.Rule.Node} */ /** * @type {Rule['Node']} */ /** * Silently ignores error * @type {Rule['Node'} */ ```` --- # reject-any-type Reports use of `any` (or `*`) type within JSDoc tag types. ||| |---|---| |Context|everywhere| |Tags|`augments`, `class`, `constant`, `enum`, `implements`, `member`, `module`, `namespace`, `param`, `property`, `returns`, `throws`, `type`, `typedef`, `yields`| |Aliases|`constructor`, `const`, `extends`, `var`, `arg`, `argument`, `prop`, `return`, `exception`, `yield`| |Closure-only|`package`, `private`, `protected`, `public`, `static`| |Recommended|true| |Settings|`mode`| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @param {any} abc */ function quux () {} // Message: Prefer a more specific type to `any` /** * @param {*} abc */ function quux () {} // Message: Prefer a more specific type to `*` /** * @param {string|Promise} abc */ function quux () {} // Message: Prefer a more specific type to `any` /** * @param {Array<*>|number} abc */ function quux () {} // Message: Prefer a more specific type to `*` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {SomeType} abc */ function quux () {} ```` --- # reject-function-type Reports use of `Function` type within JSDoc tag types. ||| |---|---| |Context|everywhere| |Tags|`augments`, `class`, `constant`, `enum`, `implements`, `member`, `module`, `namespace`, `param`, `property`, `returns`, `throws`, `type`, `typedef`, `yields`| |Aliases|`constructor`, `const`, `extends`, `var`, `arg`, `argument`, `prop`, `return`, `exception`, `yield`| |Closure-only|`package`, `private`, `protected`, `public`, `static`| |Recommended|true| |Settings|`mode`| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @param {Function} fooBar */ function quux (fooBar) { console.log(fooBar(3)); } // Message: Prefer a more specific type to `Function` /** * @param {string|Array} abc */ function buzz (abc) {} // Message: Prefer a more specific type to `Function` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {SomeType} abc */ function quux (abc) {} // To avoid referencing a generic Function, define a callback // with its inputs/outputs and a name. /** * @callback FOOBAR * @param {number} baz * @return {number} */ // Then reference the callback name as the type. /** * @param {FOOBAR} fooBar */ function quux (fooBar) { console.log(fooBar(3)); } /** * @param {string|Array} abc */ function buzz (abc) {} ```` --- ### require-asterisk-prefix Requires that each JSDoc line starts with an `*`. ## Fixer Adds an asterisk for each missing line of the JSDoc block. ## Options The first option is a string with the following possible values: "always", "never", "any". If it is `"always"` then a problem is raised when there is no asterisk prefix on a given JSDoc line. If it is `"never"` then a problem is raised when there is an asterisk present. The default value is `"always"`. You may also set the default to `"any"` and use the `tags` option to apply to specific tags only. The next option is an object with the following properties. ### tags A single options object has the following properties. If you want different values to apply to specific tags, you may use the `tags` option object. The keys are `always`, `never`, or `any` and the values are arrays of tag names or the special value `*description` which applies to the main JSDoc block description. ```js { 'jsdoc/require-asterisk-prefix': ['error', 'always', { tags: { always: ['*description'], any: ['example', 'license'], never: ['copyright'] } }] } ``` #### always If it is `"always"` then a problem is raised when there is no asterisk prefix on a given JSDoc line. #### any No problem is raised regardless of asterisk presence or non-presence. #### never If it is `"never"` then a problem is raised when there is an asterisk present. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|All or as limited by the `tags` option| |Recommended|false| |Options|string ("always", "never", "any") followed by object with `tags`| ## Failing examples The following patterns are considered problems: ````ts /** @param {Number} foo */ function quux (foo) { // with spaces } // Message: Expected JSDoc line to have the prefix. /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "any",{"tags":{"always":["param"]}}] // Message: Expected JSDoc line to have the prefix. /** * Desc */ function quux (foo) { // with spaces } // Message: Expected JSDoc line to have the prefix. /** * Desc */ function quux (foo) { // with spaces } // Message: Expected JSDoc line to have the prefix. /** * Desc * */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never"] // Message: Expected JSDoc line to have no prefix. /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "always",{"tags":{"any":["someOtherTag"]}}] // Message: Expected JSDoc line to have the prefix. /** * @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never",{"tags":{"always":["someOtherTag"]}}] // Message: Expected JSDoc line to have no prefix. /** * @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "always",{"tags":{"never":["param"]}}] // Message: Expected JSDoc line to have no prefix. /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never",{"tags":{"always":["param"]}}] // Message: Expected JSDoc line to have the prefix. /** @param {Number} foo */function quux (foo) { // with spaces } // Message: Expected JSDoc line to have the prefix. /** * @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never"] // Message: Expected JSDoc line to have no prefix. /** *@param {Number} foo */function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never"] // Message: Expected JSDoc line to have no prefix. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * Desc * * @param {Number} foo * This is more comment. */ function quux (foo) { } /** * Desc * * @param {{ * foo: Bar, * bar: Baz * }} foo * */ function quux (foo) { } /* <- JSDoc must start with 2 stars. So this is unchecked. */ function quux (foo) {} /** @param {Number} foo */ function quux (foo) { // with spaces } /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "always",{"tags":{"any":["param"]}}] /** * @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never",{"tags":{"always":["param"]}}] /** * @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "always",{"tags":{"never":["someOtherTag"]}}] /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "always",{"tags":{"never":["param"]}}] /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never",{"tags":{"always":["someOtherTag"]}}] /** * Desc * */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "never",{"tags":{"any":["*description"]}}] /** * Desc */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "always",{"tags":{"any":["*description"]}}] /** @param {Number} foo */ function quux (foo) { // with spaces } // "jsdoc/require-asterisk-prefix": ["error"|"warn", "any",{"tags":{"always":["someOtherTag"]}}] ```` --- # require-description-complete-sentence * [Fixer](#user-content-require-description-complete-sentence-fixer) * [Options](#user-content-require-description-complete-sentence-options) * [`abbreviations`](#user-content-require-description-complete-sentence-options-abbreviations) * [`newlineBeforeCapsAssumesBadSentenceEnd`](#user-content-require-description-complete-sentence-options-newlinebeforecapsassumesbadsentenceend) * [`tags`](#user-content-require-description-complete-sentence-options-tags) * [Context and settings](#user-content-require-description-complete-sentence-context-and-settings) * [Failing examples](#user-content-require-description-complete-sentence-failing-examples) * [Passing examples](#user-content-require-description-complete-sentence-passing-examples) Requires that block description, explicit `@description`, and `@param`/`@returns` tag descriptions are written in complete sentences, i.e., * Description must start with an uppercase alphabetical character. * Paragraphs must start with an uppercase alphabetical character. * Sentences must end with a period, question mark, exclamation mark, or triple backticks. * Every line in a paragraph (except the first) which starts with an uppercase character must be preceded by a line ending with a period. * A colon or semi-colon followed by two line breaks is still part of the containing paragraph (unlike normal dual line breaks). * Text within inline tags `{...}` or within triple backticks are not checked for sentence divisions. * Periods after items within the `abbreviations` option array are not treated as sentence endings. ## Fixer If sentences do not end with terminal punctuation, a period will be added. If sentences do not start with an uppercase character, the initial letter will be capitalized. ## Options A single options object has the following properties. ### abbreviations You can provide an `abbreviations` options array to avoid such strings of text being treated as sentence endings when followed by dots. The `.` is not necessary at the end of the array items. ### newlineBeforeCapsAssumesBadSentenceEnd When `false` (the new default), we will not assume capital letters after newlines are an incorrect way to end the sentence (they may be proper nouns, for example). ### tags If you want additional tags to be checked for their descriptions, you may add them within this option. ```js { 'jsdoc/require-description-complete-sentence': ['error', { tags: ['see', 'copyright'] }] } ``` The tags `@param`/`@arg`/`@argument` and `@property`/`@prop` will be properly parsed to ensure that the checked "description" text includes only the text after the name. All other tags will treat the text following the tag name, a space, and an optional curly-bracketed type expression (and another space) as part of its "description" (e.g., for `@returns {someType} some description`, the description is `some description` while for `@some-tag xyz`, the description is `xyz`). ## Context and settings ||| |---|---| |Context|everywhere| |Tags|doc block, `param`, `returns`, `description`, `property`, `summary`, `file`, `classdesc`, `todo`, `deprecated`, `throws`, 'yields' and others added by `tags`| |Aliases|`arg`, `argument`, `return`, `desc`, `prop`, `fileoverview`, `overview`, `exception`, `yield`| |Recommended|false| |Options|`abbreviations`, `newlineBeforeCapsAssumesBadSentenceEnd`, `tags`| ## Failing examples The following patterns are considered problems: ````ts /** * foo. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * foo? */ function quux () { } // Message: Sentences should start with an uppercase character. /** * @description foo. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * Foo) */ function quux () { } // Message: Sentences must end with a period. /** * `foo` is a variable */ function quux () { } // Message: Sentences must end with a period. /** * Foo. * * foo. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * тест. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * Foo */ function quux () { } // Message: Sentences must end with a period. /** * Foo * * @param x */ function quux () { } // Message: Sentences must end with a period. /** * Foo * Bar. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"newlineBeforeCapsAssumesBadSentenceEnd":true}] // Message: A line of text is started with an uppercase character, but the preceding line does not end the sentence. /** * Foo. * * @param foo foo. */ function quux (foo) { } // Message: Sentences should start with an uppercase character. /** * Foo. * * @param foo bar */ function quux (foo) { } // Message: Sentences should start with an uppercase character. /** * {@see Foo.bar} buz */ function quux (foo) { } // Message: Sentences must end with a period. /** * Foo. * * @returns {number} foo */ function quux (foo) { } // Message: Sentences should start with an uppercase character. /** * Foo. * * @returns foo. */ function quux (foo) { } // Message: Sentences should start with an uppercase character. /** * lorem ipsum dolor sit amet, consectetur adipiscing elit. pellentesque elit diam, * iaculis eu dignissim sed, ultrices sed nisi. nulla at ligula auctor, consectetur neque sed, * tincidunt nibh. vivamus sit amet vulputate ligula. vivamus interdum elementum nisl, * vitae rutrum tortor semper ut. morbi porta ante vitae dictum fermentum. * proin ut nulla at quam convallis gravida in id elit. sed dolor mauris, blandit quis ante at, * consequat auctor magna. duis pharetra purus in porttitor mollis. */ function longDescription (foo) { } // Message: Sentences should start with an uppercase character. /** * @arg {number} foo - Foo */ function quux (foo) { } // Message: Sentences must end with a period. /** * @argument {number} foo - Foo */ function quux (foo) { } // Message: Sentences must end with a period. /** * @return {number} foo */ function quux (foo) { } // Message: Sentences should start with an uppercase character. /** * Returns bar. * * @return {number} bar */ function quux (foo) { } // Message: Sentences should start with an uppercase character. /** * @throws {object} Hello World * hello world */ // Message: Sentences must end with a period. /** * @summary Foo */ function quux () { } // Message: Sentences must end with a period. /** * @throws {SomeType} Foo */ function quux () { } // Message: Sentences must end with a period. /** * @see Foo */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"tags":["see"]}] // Message: Sentences must end with a period. /** * @param foo Foo bar */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"tags":["param"]}] // Message: Sentences must end with a period. /** * Sorry, but this isn't a complete sentence, Mr. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr"]}] // Message: Sentences must end with a period. /** * Sorry, but this isn't a complete sentence Mr. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr."]}] // Message: Sentences must end with a period. /** * Sorry, but this isn't a complete sentence Mr. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr"]}] // Message: Sentences must end with a period. /** * Sorry, but this isn't a complete sentence Mr. and Mrs. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr","Mrs"]}] // Message: Sentences must end with a period. /** * This is a complete sentence. But this isn't, Mr. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr"]}] // Message: Sentences must end with a period. /** * This is a complete Mr. sentence. But this isn't, Mr. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr"]}] // Message: Sentences must end with a period. /** * This is a complete Mr. sentence. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * This is fun, i.e. enjoyable, but not superlatively so, e.g. not * super, wonderful, etc.. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * Do not have dynamic content; e.g. homepage. Here a simple unique id * suffices. */ function quux () { } // Message: Sentences should start with an uppercase character. /** * Implements support for the * Swahili voice synthesizer. */ function speak() { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"newlineBeforeCapsAssumesBadSentenceEnd":true}] // Message: A line of text is started with an uppercase character, but the preceding line does not end the sentence. /** * Foo. * * @template TempA, TempB foo. */ function quux (foo) { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"tags":["template"]}] // Message: Sentences should start with an uppercase character. /** * Just a component. * @param {Object} props Свойства. * @return {ReactElement}. */ function quux () {} // Message: Sentences must be more than punctuation. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param foo - Foo. */ function quux () { } /** * Foo. */ function quux () { } /** * Foo. * Bar. */ function quux () { } /** * Foo. * * Bar. */ function quux () { } /** * Тест. */ function quux () { } /** * Foo * bar. */ function quux () { } /** * @returns Foo bar. */ function quux () { } /** * Foo {@see Math.sin}. */ function quux () { } /** * Foo {@see Math.sin} bar. */ function quux () { } /** * Foo? * * Bar! * * Baz: * 1. Foo. * 2. Bar. */ function quux () { } /** * Hello: * World. */ function quux () { } /** * Hello: world. */ function quux () { } /** * */ function quux () { } /** * @description Foo. */ function quux () { } /** * `foo` is a variable. */ function quux () { } /** * Foo. * * `foo`. */ function quux () { } /** * @param foo - `bar`. */ function quux () { } /** * @returns {number} `foo`. */ function quux () { } /** * Foo * `bar`. */ function quux () { } /** * @example Foo */ function quux () { } /** * @see Foo */ function quux () { } /** * Foo. * * @param foo Foo. */ function quux (foo) { } /** * Foo. * * @param foo Foo. */ function quux (foo) { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"tags":["param"]}] /** * @param foo Foo bar. */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"tags":["param"]}] /** * */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} /** * We stop loading Items when we have loaded: * * 1) The main Item; * 2) All its variants. */ /** * This method is working on 2 steps. * * | Step | Comment | * |------|-------------| * | 1 | do it | * | 2 | do it again | */ /** * This is something that * I want to test. */ function quux () { } /** * When making HTTP requests, the * URL is super important. */ function quux () { } /** * Sorry, but this isn't a complete sentence, Mr. */ function quux () { } /** * Sorry, but this isn't a complete sentence Mr.. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr."]}] /** * Sorry, but this isn't a complete sentence Mr. */ function quux () { } /** * Sorry, but this isn't a complete sentence Mr. and Mrs.. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr","Mrs"]}] /** * This is a complete sentence aMr. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr"]}] /** * This is a complete sentence. But this isn't, Mr. */ function quux () { } /** * This is a complete Mr. Sentence. But this isn't, Mr. */ function quux () { } /** * This is a complete Mr. sentence. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["Mr"]}] /** * This is fun, i.e. enjoyable, but not superlatively so, e.g. not * super, wonderful, etc.. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["etc","e.g.","i.e."]}] ** * Do not have dynamic content; e.g. homepage. Here a simple unique id * suffices. */ function quux () { } // "jsdoc/require-description-complete-sentence": ["error"|"warn", {"abbreviations":["etc","e.g.","i.e."]}] /** * Implements support for the * Swahili voice synthesizer. */ function speak() { } /** * @param foo * * @returns {void} */ export default (foo) => { foo() } /** @file To learn more, * see: https://github.com/d3/d3-ease. */ /** To learn more, * see: https://github.com/d3/d3-ease. */ /** * This is a complete sentence... */ function quux () { } /** * He wanted a few items: a jacket and shirt... */ function quux () { } /** * The code in question was... * ``` * alert('hello'); * ``` */ function quux () { } /** * @param {number|string|Date|Object|OverType|WhateverElse} multiType - * Nice long explanation... */ function test (multiType) { } /** * Any kind of fowl (e.g., a duck). */ function quux () {} /** * The code in question was... * ``` * do something * * interesting * ``` */ function quux () { } /** @param options {@link RequestOptions} specifying path parameters and query parameters. */ /** * A single line for testing. * * ```js * const aCodeExample = true; * ``` * * @param parameter */ const code = (parameter) => 123; /** * ### Overview * My class is doing. * * ### Example * ```javascript * const toto = 'toto'; * ``` */ export class ClassExemple { } ```` --- # require-description * [Options](#user-content-require-description-options) * [`checkConstructors`](#user-content-require-description-options-checkconstructors) * [`checkGetters`](#user-content-require-description-options-checkgetters) * [`checkSetters`](#user-content-require-description-options-checksetters) * [`contexts`](#user-content-require-description-options-contexts) * [`descriptionStyle`](#user-content-require-description-options-descriptionstyle) * [`exemptedBy`](#user-content-require-description-options-exemptedby) * [Context and settings](#user-content-require-description-context-and-settings) * [Failing examples](#user-content-require-description-failing-examples) * [Passing examples](#user-content-require-description-passing-examples) Requires that all functions (or optionally other structures) with a JSDoc block have a description. * All functions must have an implicit description (e.g., text above tags) or have the option `descriptionStyle` set to `tag` (requiring `@description` (or `@desc` if that is set as your preferred tag name)). * Every JSDoc block description (or `@description` tag if `descriptionStyle` is `"tag"`) must have a non-empty description that explains the purpose of the method. ## Options A single options object has the following properties. ### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. ### checkGetters A value indicating whether getters should be checked. Defaults to `true`. ### checkSetters A value indicating whether setters should be checked. Defaults to `true`. ### contexts Set to an array of strings representing the AST context where you wish the rule to be applied (e.g., `ClassDeclaration` for ES6 classes). `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### descriptionStyle Whether to accept implicit descriptions (`"body"`) or `@description` tags (`"tag"`) as satisfying the rule. Set to `"any"` to accept either style. Defaults to `"body"`. ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@description`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ## Context and settings | | | | -------- | ---------------------- | | Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled | | Tags | `description` or JSDoc block | | Aliases | `desc` | | Recommended | false | | Options |`checkConstructors`, `checkGetters`, `checkSetters`, `contexts`, `descriptionStyle`, `exemptedBy`| | Settings | `ignoreReplacesDocs`, `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` | ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"any"}] // Message: Missing JSDoc block description or @description declaration. /** * */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"body"}] // Message: Missing JSDoc block description. /** * @desc Not a blank description */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"body"}] // Message: Remove the @desc tag to leave a plain block description or add additional description text above the @desc line. /** * @description Not a blank description */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"body"}] // Message: Remove the @description tag to leave a plain block description or add additional description text above the @description line. /** * */ class quux { } // "jsdoc/require-description": ["error"|"warn", {"contexts":["ClassDeclaration"],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * */ class quux { } // Settings: {"jsdoc":{"contexts":["ClassDeclaration"]}} // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * */ // "jsdoc/require-description": ["error"|"warn", {"contexts":["any"],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * @description */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] // Message: Missing JSDoc @description description. /** * */ interface quux { } // "jsdoc/require-description": ["error"|"warn", {"contexts":["TSInterfaceDeclaration"],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * */ var quux = class { }; // "jsdoc/require-description": ["error"|"warn", {"contexts":["ClassExpression"],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * */ var quux = { }; // "jsdoc/require-description": ["error"|"warn", {"contexts":["ObjectExpression"],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * @someDesc */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"description":{"message":"Please avoid `{{tagName}}`; use `{{replacement}}` instead","replacement":"someDesc"}}}} // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] // Message: Missing JSDoc @someDesc description. /** * @description */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] // Message: Unexpected tag `@description` /** * @description */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"any"}] // Message: Missing JSDoc block description or @description declaration. /** * */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"exemptedBy":["notPresent"]}] // Message: Missing JSDoc block description. class TestClass { /** * */ constructor() { } } // Message: Missing JSDoc block description. class TestClass { /** * */ constructor() { } } // "jsdoc/require-description": ["error"|"warn", {"checkConstructors":true}] // Message: Missing JSDoc block description. class TestClass { /** * */ get Test() { } } // Message: Missing JSDoc block description. class TestClass { /** * */ get Test() { } } // "jsdoc/require-description": ["error"|"warn", {"checkGetters":true}] // Message: Missing JSDoc block description. class TestClass { /** * */ set Test(value) { } } // Message: Missing JSDoc block description. class TestClass { /** * */ set Test(value) { } } // "jsdoc/require-description": ["error"|"warn", {"checkSetters":true}] // Message: Missing JSDoc block description. /** * */ class Foo { /** * */ constructor() {} /** * */ bar() {} } // "jsdoc/require-description": ["error"|"warn", {"checkConstructors":false,"contexts":["MethodDefinition"]}] // Message: Missing JSDoc block description. /** * @implements {Bar} */ class quux { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[rawType=\"Bar\"])","context":"ClassDeclaration"}],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * Has some * description already. * @implements {Bar} */ class quux { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[rawType=\"Bar\"])","context":"ClassDeclaration"}],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * @implements {Bar * | Foo} */ class quux { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTypeUnion > JsdocTypeName[value=\"Bar\"]:nth-child(1))","context":"ClassDeclaration"}],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * @implements {Bar} */ class quux { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[tag=\"implements\"])","context":"ClassDeclaration"}],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. /** * @implements {Bar} */ class quux { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[tag=\"implements\"])","context":"any"}],"descriptionStyle":"tag"}] // Message: Missing JSDoc @description declaration. app.use( /** @type {express.ErrorRequestHandler} */ (err, req, res, next) => { // foo } ); // Message: Missing JSDoc block description. app.use( /** @type {express.ErrorRequestHandler} */ ( (err, req, res, next) => { // foo } ) ); // Message: Missing JSDoc block description. /** @type {TreeViewItemData[]} */ this.treeViewSelection = []; // "jsdoc/require-description": ["error"|"warn", {"contexts":["AssignmentExpression"]}] // Message: Missing JSDoc block description. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ /** * @description * // arbitrary description content */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * @description * quux(); // does something useful */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * @description Valid usage * quux(); // does something useful * * @description Invalid usage * quux('random unwanted arg'); // results in an error */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * */ class quux { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"contexts":["ClassDeclaration"]}] /** * @type {MyCallback} */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"exemptedBy":["type"]}] /** * */ interface quux { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] interface quux { /** * If the thing should be checked. */ checked?: boolean } // "jsdoc/require-description": ["error"|"warn", {"contexts":["TSPropertySignature"]}] /** * */ var quux = class { }; // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * */ var quux = { }; // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * Has an implicit description */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"body"}] /** * Has an implicit description */ function quux () { } /** * Has an implicit description */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"any"}] /** * @description Has an explicit description */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"any"}] /** * */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"description":false}}} class TestClass { /** * Test. */ constructor() { } } class TestClass { /** * */ constructor() { } } // "jsdoc/require-description": ["error"|"warn", {"checkConstructors":false}] class TestClass { /** * Test. */ get Test() { } } class TestClass { /** * */ get Test() { } } // "jsdoc/require-description": ["error"|"warn", {"checkGetters":false}] class TestClass { /** * Test. */ set Test(value) { } } class TestClass { /** * */ set Test(value) { } } // "jsdoc/require-description": ["error"|"warn", {"checkSetters":false}] /** * Multi * line */ function quux () { } /** Single line */ function quux () { } /** @description something */ function quux () { } // "jsdoc/require-description": ["error"|"warn", {"descriptionStyle":"tag"}] /** * @implements {Bar} */ class quux { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=/\\s{4}/]:has(JsdocTag[rawType=\"class\"])","context":"ClassDeclaration"}],"descriptionStyle":"tag"}] /** * Has some * description already. */ class quux { } // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[rawType=\"{Bar}\"])","context":"ClassDeclaration"}],"descriptionStyle":"tag"}] /** * Has some * description already. */ class quux { } // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[rawType=\"{Bar}\"])","context":"any"}],"descriptionStyle":"tag"}] /** * Has some * description already. */ // "jsdoc/require-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock[postDelimiter=\"\"]:has(JsdocTag[rawType=\"{Bar}\"])","context":"any"}],"descriptionStyle":"tag"}] ```` --- # require-example * [Fixer](#user-content-require-example-fixer) * [Options](#user-content-require-example-options) * [`checkConstructors`](#user-content-require-example-options-checkconstructors) * [`checkGetters`](#user-content-require-example-options-checkgetters) * [`checkSetters`](#user-content-require-example-options-checksetters) * [`contexts`](#user-content-require-example-options-contexts) * [`enableFixer`](#user-content-require-example-options-enablefixer) * [`exemptedBy`](#user-content-require-example-options-exemptedby) * [`exemptNoArguments`](#user-content-require-example-options-exemptnoarguments) * [Context and settings](#user-content-require-example-context-and-settings) Requires that all functions have examples. * All functions must have one or more `@example` tags. * Every example tag must have a non-empty description that explains the method's usage. ## Fixer The fixer for `require-example` will add an empty `@example`, but it will still report a missing example description after this is added. ## Options A single options object has the following properties. ### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. ### checkGetters A value indicating whether getters should be checked. Defaults to `false`. ### checkSetters A value indicating whether setters should be checked. Defaults to `false`. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. (e.g., `ClassDeclaration` for ES6 classes). `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files. See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### enableFixer A boolean on whether to enable the fixer (which adds an empty `@example` block). Defaults to `true`. ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for an `@example`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ### exemptNoArguments Boolean to indicate that no-argument functions should not be reported for missing `@example` declarations. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`example`| |Recommended|false| |Options|`checkConstructors`, `checkGetters`, `checkSetters`, `contexts`, `enableFixer`, `exemptedBy`, `exemptNoArguments`| |Settings|`ignoreReplacesDocs`, `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs`| # Failing examples The following patterns are considered problems: ````ts /** * */ function quux () { } // Message: Missing JSDoc @example declaration. /** * */ function quux (someParam) { } // "jsdoc/require-example": ["error"|"warn", {"exemptNoArguments":true}] // Message: Missing JSDoc @example declaration. /** * */ function quux () { } // Message: Missing JSDoc @example declaration. /** * @example */ function quux () { } // Message: Missing JSDoc @example description. /** * @constructor */ function quux () { } // Message: Missing JSDoc @example declaration. /** * @constructor * @example */ function quux () { } // Message: Missing JSDoc @example description. /** * */ class quux { } // "jsdoc/require-example": ["error"|"warn", {"contexts":["ClassDeclaration"]}] // Message: Missing JSDoc @example declaration. /** * */ // "jsdoc/require-example": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @example declaration. /** * */ function quux () { } // "jsdoc/require-example": ["error"|"warn", {"exemptedBy":["notPresent"]}] // Message: Missing JSDoc @example declaration. class TestClass { /** * */ get Test() { } } // "jsdoc/require-example": ["error"|"warn", {"checkGetters":true}] // Message: Missing JSDoc @example declaration. class TestClass { /** * @example */ get Test() { } } // "jsdoc/require-example": ["error"|"warn", {"checkGetters":true}] // Message: Missing JSDoc @example description. class TestClass { /** * */ set Test(value) { } } // "jsdoc/require-example": ["error"|"warn", {"checkSetters":true}] // Message: Missing JSDoc @example declaration. class TestClass { /** * @example */ set Test(value) { } } // "jsdoc/require-example": ["error"|"warn", {"checkSetters":true}] // Message: Missing JSDoc @example description. /** * */ function quux (someParam) { } // "jsdoc/require-example": ["error"|"warn", {"enableFixer":true}] // Message: Missing JSDoc @example declaration. /** * */ function quux (someParam) { } // "jsdoc/require-example": ["error"|"warn", {"enableFixer":false}] // Message: Missing JSDoc @example declaration. /** * Returns a Promise... * * @param {number} ms - The number of ... */ const sleep = (ms: number): Promise => {}; // "jsdoc/require-example": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @example declaration. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ /** * @example * // arbitrary example content */ function quux () { } /** * @example * quux(); // does something useful */ function quux () { } /** * @example Valid usage * quux(); // does something useful * * @example Invalid usage * quux('random unwanted arg'); // results in an error */ function quux () { } /** * @constructor */ function quux () { } // "jsdoc/require-example": ["error"|"warn", {"checkConstructors":false}] /** * @constructor * @example */ function quux () { } // "jsdoc/require-example": ["error"|"warn", {"checkConstructors":false}] class Foo { /** * */ constructor () { } } // "jsdoc/require-example": ["error"|"warn", {"checkConstructors":false}] /** * @inheritdoc */ function quux () { } /** * @type {MyCallback} */ function quux () { } // "jsdoc/require-example": ["error"|"warn", {"exemptedBy":["type"]}] /** * @example Some example code */ class quux { } // "jsdoc/require-example": ["error"|"warn", {"contexts":["ClassDeclaration"]}] /** * */ function quux () { } // "jsdoc/require-example": ["error"|"warn", {"contexts":["ClassDeclaration"]}] class TestClass { /** * */ get Test() { } } class TestClass { /** * @example */ get Test() { } } class TestClass { /** * @example Test */ get Test() { } } // "jsdoc/require-example": ["error"|"warn", {"checkGetters":true}] class TestClass { /** * */ set Test(value) { } } class TestClass { /** * @example */ set Test(value) { } } // "jsdoc/require-example": ["error"|"warn", {"checkSetters":false}] class TestClass { /** * @example Test */ set Test(value) { } } // "jsdoc/require-example": ["error"|"warn", {"checkSetters":true}] /** * */ function quux () { } // "jsdoc/require-example": ["error"|"warn", {"exemptNoArguments":true}] ```` --- # require-file-overview * [Options](#user-content-require-file-overview-options) * [`tags`](#user-content-require-file-overview-options-tags) * [Context and settings](#user-content-require-file-overview-context-and-settings) * [Failing examples](#user-content-require-file-overview-failing-examples) * [Passing examples](#user-content-require-file-overview-passing-examples) Checks that: 1. All files have a `@file`, `@fileoverview`, or `@overview` tag. 2. Duplicate file overview tags within a given file will be reported 3. File overview tags will be reported which are not, as per [the docs](https://jsdoc.app/tags-file.html), "at the beginning of the file"–where beginning of the file is interpreted in this rule as being when the overview tag is not preceded by anything other than a comment. ## Options A single options object has the following properties. ### tags The keys of this object are tag names, and the values are configuration objects indicating what will be checked for these whole-file tags. Each configuration object has 3 potential boolean keys (which default to `false` when this option is supplied). 1. `mustExist` - enforces that all files have a `@file`, `@fileoverview`, or `@overview` tag. 2. `preventDuplicates` - enforces that duplicate file overview tags within a given file will be reported 3. `initialCommentsOnly` - reports file overview tags which are not, as per [the docs](https://jsdoc.app/tags-file.html), "at the beginning of the file"–where beginning of the file is interpreted in this rule as being when the overview tag is not preceded by anything other than a comment. When no `tags` is present, the default is: ```json { "file": { "initialCommentsOnly": true, "mustExist": true, "preventDuplicates": true, } } ``` You can add additional tag names and/or override `file` if you supply this option, e.g., in place of or in addition to `file`, giving other potential file global tags like `@license`, `@copyright`, `@author`, `@module` or `@exports`, optionally restricting them to a single use or preventing them from being preceded by anything besides comments. For example: ```js { "license": { "mustExist": true, "preventDuplicates": true, } } ``` This would require one and only one `@license` in the file, though because `initialCommentsOnly` is absent and defaults to `false`, the `@license` can be anywhere. In the case of `@license`, you can use this rule along with the `check-values` rule (with its `allowedLicenses` or `licensePattern` options), to enforce a license whitelist be present on every JS file. Note that if you choose to use `preventDuplicates` with `license`, you still have a way to allow multiple licenses for the whole page by using the SPDX "AND" expression, e.g., `@license (MIT AND GPL-3.0)`. Note that the tag names are the main JSDoc tag name, so you should use `file` in this configuration object regardless of whether you have configured `fileoverview` instead of `file` on `tagNamePreference` (i.e., `fileoverview` will be checked, but you must use `file` on the configuration object). ## Context and settings ||| |---|---| |Context|Everywhere| |Tags|`file`; others when `tags` set| |Aliases|`fileoverview`, `overview`| |Recommended|false| |Options|`tags`| ## Failing examples The following patterns are considered problems: ````ts // Message: Missing @file // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"file":{"initialCommentsOnly":true,"mustExist":true,"preventDuplicates":true}}}] // Message: Missing @file // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"file":{"mustExist":true}}}] // Message: Missing @file // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"author":{"initialCommentsOnly":false,"mustExist":true,"preventDuplicates":false}}}] // Message: Missing @author /** * */ // Message: Missing @file /** * */ function quux () {} // Message: Missing @file /** * */ function quux () {} // Settings: {"jsdoc":{"tagNamePreference":{"file":"fileoverview"}}} // Message: Missing @fileoverview /** * */ function quux () {} // Settings: {"jsdoc":{"tagNamePreference":{"file":"overview"}}} // Message: Missing @overview /** * */ function quux () {} // Settings: {"jsdoc":{"tagNamePreference":{"file":false}}} // Message: `settings.jsdoc.tagNamePreference` cannot block @file for the `require-file-overview` rule /** * */ function quux () {} // Settings: {"jsdoc":{"tagNamePreference":{"file":false}}} // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"file":{"initialCommentsOnly":false,"mustExist":true,"preventDuplicates":false}}}] // Message: `settings.jsdoc.tagNamePreference` cannot block @file for the `require-file-overview` rule /** * */ function quux () {} // Settings: {"jsdoc":{"tagNamePreference":{"file":{"message":"Don't use file"}}}} // Message: `settings.jsdoc.tagNamePreference` cannot block @file for the `require-file-overview` rule /** * @param a */ function quux (a) {} // Message: Missing @file /** * @param a */ function quux (a) {} /** * @param b */ function bar (b) {} // Message: Missing @file /** * @file */ /** * @file */ // Message: Duplicate @file /** * @copyright */ /** * @copyright */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"copyright":{"initialCommentsOnly":false,"mustExist":false,"preventDuplicates":true}}}] // Message: Duplicate @copyright function quux () { } /** * @file */ // Message: @file should be at the beginning of the file function quux () { } /** * @license */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":true,"mustExist":false,"preventDuplicates":false}}}] // Message: @license should be at the beginning of the file function quux () { } /** * @license */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":true}}}] // Message: @license should be at the beginning of the file /** * @file */ /** * @file */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"file":{"initialCommentsOnly":true,"preventDuplicates":true}}}] // Message: Duplicate @file /** * */ function quux () {} // Settings: {"jsdoc":{"tagNamePreference":{"file":{"replacement":"fileoverview"}}}} // Message: Missing @fileoverview ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @file */ /** * @file */ /** * @file */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":true,"preventDuplicates":true}}}] // Ok preceded by comment /** * @file */ /** * @fileoverview */ // Settings: {"jsdoc":{"tagNamePreference":{"file":"fileoverview"}}} /** * @overview */ // Settings: {"jsdoc":{"tagNamePreference":{"file":"overview"}}} /** * @file Description of file */ /** * @file Description of file */ function quux () { } /** * */ function quux () { } /** * */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":true,"mustExist":false,"preventDuplicates":false}}}] function quux () { } /** * */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":false,"mustExist":false,"preventDuplicates":false}}}] function quux () { } /** * */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":false,"mustExist":false,"preventDuplicates":true}}}] /** * @license MIT */ var a /** * @type {Array} */ // "jsdoc/require-file-overview": ["error"|"warn", {"tags":{"license":{"initialCommentsOnly":true,"mustExist":false,"preventDuplicates":false}}}] ```` --- # require-hyphen-before-param-description * [Fixer](#user-content-require-hyphen-before-param-description-fixer) * [Options](#user-content-require-hyphen-before-param-description-options) * [`tags`](#user-content-require-hyphen-before-param-description-options-tags) * [Context and settings](#user-content-require-hyphen-before-param-description-context-and-settings) * [Failing examples](#user-content-require-hyphen-before-param-description-failing-examples) * [Passing examples](#user-content-require-hyphen-before-param-description-passing-examples) Requires (or disallows) a hyphen before the `@param` description. ## Fixer Adds a hyphen for "always" and removes a hyphen for "never". ## Options The first option is a string with the following possible values: "always", "never". If the string is `"always"` then a problem is raised when there is no hyphen before the description. If it is `"never"` then a problem is raised when there is a hyphen before the description. The default value is `"always"`. Even if hyphens are set to "always" appear after the tag name, they will actually be forbidden in the event that they are followed immediately by the end of a line (this will otherwise cause Visual Studio Code to display incorrectly). The next option is an object with the following properties. The options object may have the following property to indicate behavior for other tags besides the `@param` tag (or the `@arg` tag if so set). ### tags Object whose keys indicate different tags to check for the presence or absence of hyphens; the key value should be "always" or "never", indicating how hyphens are to be applied, e.g., `{property: 'never'}` to ensure `@property` never uses hyphens. A key can also be set as `*`, e.g., `'*': 'always'` to apply hyphen checking to any tag (besides the preferred `@param` tag which follows the main string option setting and besides any other `tags` entries). ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`param` and optionally other tags within `tags`| |Aliases|`arg`, `argument`; potentially `prop` or other aliases| |Recommended|false| |Options|string ("always", "never") followed by object with `tags`| ## Failing examples The following patterns are considered problems: ````ts /** * @param foo Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always"] // Message: There must be a hyphen before @param description. /** * @param foo Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"*":"never"}}] // Message: There must be a hyphen before @param description. /** * @param foo Foo. * @returns {SomeType} - Hyphen here. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"*":"never","returns":"always"}}] // Message: There must be a hyphen before @param description. /** * @param foo Foo. */ function quux () { } // Message: There must be a hyphen before @param description. /** * @param foo - Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never"] // Message: There must be no hyphen before @param description. /** * @param foo - Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never"] // Message: There must be no hyphen before @param description. /** * @param foo - foo * @param foo foo */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always"] // Message: There must be a hyphen before @param description. /** * @param foo foo * bar * @param bar - bar */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always"] // Message: There must be a hyphen before @param description. /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":false}}} // Message: Unexpected tag `@param` /** * @typedef {SomeType} ATypeDefName * @property foo Foo. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"property":"always"}}] // Message: There must be a hyphen before @property description. /** * @template TempA, TempB A desc. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"template":"always"}}] // Message: There must be a hyphen before @template description. /** * @typedef {SomeType} ATypeDefName * @property foo - Foo. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never",{"tags":{"property":"never"}}] // Message: There must be no hyphen before @property description. /** * @param foo Foo. * @returns {SomeType} - A description. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"returns":"never"}}] // Message: There must be a hyphen before @param description. /** * Split a unit to metric prefix and basic unit. * * @param {string} unit - Unit to split. * @param {string} [basicUnit] - Basic unit regardless of the metric prefix. * If omitted, basic unit will be inferred by trying to remove the metric * prefix in `unit`. * * @returns {{ prefix: string, basicUnit: string }} - Split result. * If `unit` does not have a metric prefix, `''` is returned for `prefix`. * If `unit` does not have a basic unit, `''` is returned for `basicUnit`. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"*":"never","property":"always"}}] // Message: There must be no hyphen before @returns description. /** * @returns {{ * prefix: string, basicUnit: string * }} - Split result. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"*":"never","property":"always"}}] // Message: There must be no hyphen before @returns description. /** * @param {( * | string * | number * )} input The input value */ function test(input) {} // Message: There must be a hyphen before @param description. /** * @param foo - * The possible values for `foo` are as follows. * - `"option1"`: Description of option 1. * - `"option2"`: Description of option 2. */ // Message: There must be no hyphen followed by newline after the @param name. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param foo - Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always"] /** * @param foo - Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always"] /** * @param foo - Foo. * @returns {SomeType} A description. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"returns":"never"}}] /** * @param foo Foo. */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never"] /** * @param foo */ function quux () { } /** * */ function quux () { } // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"*":"always"}}] /** * @typedef {SomeType} ATypeDefName * @property foo - Foo. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"property":"always"}}] /** * @typedef {SomeType} ATypeDefName * @property foo Foo. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never",{"tags":{"property":"never"}}] /** * @typedef {SomeType} ATypeDefName * @property foo - Foo. */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never",{"tags":{"*":"always"}}] /** Entry point for module. * * @param {!Array} argv Command-line arguments. */ function main(argv) { }; // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "never"] /** * @template {any} T - Arg 1 * @template {string | number} K - Arg 2 * @template {any} [R=(K extends keyof T ? T[K] : never)] - Arg 3 -> Errors here * @typedef {any} Test */ // "jsdoc/require-hyphen-before-param-description": ["error"|"warn", "always",{"tags":{"template":"always"}}] /** * @param foo - The possible values for `foo` are as follows. * - `"option1"`: Description of option 1. * - `"option2"`: Description of option 2. */ /** * @param foo * The possible values for `foo` are as follows. * - `"option1"`: Description of option 1. * - `"option2"`: Description of option 2. */ /** * @param foo * - `"option1"`: Description of option 1. * - `"option2"`: Description of option 2. */ ```` --- # require-jsdoc * [Fixer](#user-content-require-jsdoc-fixer) * [Options](#user-content-require-jsdoc-options) * [`checkAllFunctionExpressions`](#user-content-require-jsdoc-options-checkallfunctionexpressions) * [`checkConstructors`](#user-content-require-jsdoc-options-checkconstructors) * [`checkGetters`](#user-content-require-jsdoc-options-checkgetters) * [`checkSetters`](#user-content-require-jsdoc-options-checksetters) * [`contexts`](#user-content-require-jsdoc-options-contexts) * [`enableFixer`](#user-content-require-jsdoc-options-enablefixer) * [`exemptEmptyConstructors`](#user-content-require-jsdoc-options-exemptemptyconstructors) * [`exemptEmptyFunctions`](#user-content-require-jsdoc-options-exemptemptyfunctions) * [`exemptOverloadedImplementations`](#user-content-require-jsdoc-options-exemptoverloadedimplementations) * [`fixerMessage`](#user-content-require-jsdoc-options-fixermessage) * [`minLineCount`](#user-content-require-jsdoc-options-minlinecount) * [`publicOnly`](#user-content-require-jsdoc-options-publiconly) * [`require`](#user-content-require-jsdoc-options-require) * [`skipInterveningOverloadedDeclarations`](#user-content-require-jsdoc-options-skipinterveningoverloadeddeclarations) * [Context and settings](#user-content-require-jsdoc-context-and-settings) * [Failing examples](#user-content-require-jsdoc-failing-examples) * [Passing examples](#user-content-require-jsdoc-passing-examples) Checks for presence of JSDoc comments, on class declarations as well as functions. ## Fixer Adds an empty JSDoc block unless `enableFixer` is set to `false`. See the `contexts` option for how `inlineCommentBlock` can control the style of the generated JSDoc block and `fixerMessage` for an optional message to insert. ## Options A single options object has the following properties. Has the following optional keys. ### checkAllFunctionExpressions Normally, when `FunctionExpression` is checked, additional checks are added to check the parent contexts where reporting is likely to be desired. If you really want to check *all* function expressions, then set this to `true`. ### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. When `true`, `exemptEmptyConstructors` may still avoid reporting when no parameters or return values are found. ### checkGetters A value indicating whether getters should be checked. Besides setting as a boolean, this option can be set to the string `"no-setter"` to indicate that getters should be checked but only when there is no setter. This may be useful if one only wishes documentation on one of the two accessors. Defaults to `false`. ### checkSetters A value indicating whether setters should be checked. Besides setting as a boolean, this option can be set to the string `"no-getter"` to indicate that setters should be checked but only when there is no getter. This may be useful if one only wishes documentation on one of the two accessors. Defaults to `false`. ### contexts Set this to an array of strings or objects representing the additional AST contexts where you wish the rule to be applied (e.g., `Property` for properties). If specified as an object, it should have a `context` property and can have an `inlineCommentBlock` property which, if set to `true`, will add an inline `/** */` instead of the regular, multi-line, indented jsdoc block which will otherwise be added. Defaults to an empty array. Contexts may also have their own `minLineCount` property which is an integer indicating a minimum number of lines expected for a node in order for it to require documentation. Note that you may need to disable `require` items (e.g., `MethodDefinition`) if you are specifying a more precise form in `contexts` (e.g., `MethodDefinition:not([accessibility="private"] > FunctionExpression`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### enableFixer A boolean on whether to enable the fixer (which adds an empty JSDoc block). Defaults to `true`. ### exemptEmptyConstructors When `true`, the rule will not report missing JSDoc blocks above constructors with no parameters or return values (this is enabled by default as the class name or description should be seen as sufficient to convey intent). Defaults to `true`. ### exemptEmptyFunctions When `true`, the rule will not report missing JSDoc blocks above functions/methods with no parameters or return values (intended where function/method names are sufficient for themselves as documentation). Defaults to `false`. ### exemptOverloadedImplementations If set to `true` will avoid checking an overloaded function's implementation. Defaults to `false`. ### fixerMessage An optional message to add to the inserted JSDoc block. Defaults to the empty string. ### minLineCount An integer to indicate a minimum number of lines expected for a node in order for it to require documentation. Defaults to `undefined`. This option will apply to any context; see `contexts` for line counts specific to a context. ### publicOnly This option will insist that missing JSDoc blocks are only reported for function bodies / class declarations that are exported from the module. May be a boolean or object. If set to `true`, the defaults below will be used. If unset, JSDoc block reporting will not be limited to exports. This object supports the following optional boolean keys (`false` unless otherwise noted): - `ancestorsOnly` - Optimization to only check node ancestors to check if node is exported - `esm` - ESM exports are checked for JSDoc comments (Defaults to `true`) - `cjs` - CommonJS exports are checked for JSDoc comments (Defaults to `true`) - `window` - Window global exports are checked for JSDoc comments ### require A single options object has the following properties. An object with the following optional boolean keys which all default to `false` except for `FunctionDeclaration` which defaults to `true`. #### ArrowFunctionExpression Whether to check arrow functions like `() => {}` #### ClassDeclaration Whether to check declarations like `class A {}` #### ClassExpression Whether to check class expressions like `const myClass = class {}` #### FunctionDeclaration Whether to check function declarations like `function a {}` #### FunctionExpression Whether to check function expressions like `const a = function {}` #### MethodDefinition Whether to check method definitions like `class A { someMethodDefinition () {} }` ### skipInterveningOverloadedDeclarations If `true`, will skip above uncommented overloaded functions to check for a comment block (e.g., at the top of a set of overloaded functions). If `false`, will force each overloaded function to be checked for a comment block. Defaults to `true`. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `ClassDeclaration`, `ClassExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|N/A| |Recommended|true| |Options|`publicOnly`, `require`, `contexts`, `exemptEmptyConstructors`, `exemptEmptyFunctions`, `enableFixer`, `minLineCount`, `fixerMessage`, `skipInterveningOverloadedDeclarations`| ## Failing examples The following patterns are considered problems: ````ts /** This is comment */ export interface Foo { /** This is comment x2 */ tom: string; catchJerry(): boolean; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true},"require":{"ClassDeclaration":true,"ClassExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** This is comment */ export interface Foo { /** This is comment x2 */ tom: string; jerry: number; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true},"require":{"ClassDeclaration":true,"ClassExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** This is comment */ export interface Foo { bar(): string; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] // Message: Missing JSDoc comment. /** This is comment */ export interface Foo { bar: string; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true,"esm":true}}] // Message: Missing JSDoc comment. /** * Foo interface documentation. */ export interface Foo extends Bar { /** * baz method documentation. */ baz(): void; meow(): void; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSMethodSignature"],"publicOnly":{"ancestorsOnly":true}}] // Message: Missing JSDoc comment. function quux (foo) { } // Message: Missing JSDoc comment. /** * @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"maxLines":3,"minLines":2}} // Message: Missing JSDoc comment. /** * @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"maxLines":2}} // Message: Missing JSDoc comment. /** @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"minLines":1}} // Message: Missing JSDoc comment. function myFunction() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"enableFixer":false}] // Message: Missing JSDoc comment. export var test = function () { }; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. function test () { } export var test2 = test; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionDeclaration":true}}] // Message: Missing JSDoc comment. export const test = () => { }; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":true}}] // Message: Missing JSDoc comment. export const test = () => { }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["ArrowFunctionExpression"],"publicOnly":true}] // Message: Missing JSDoc comment. export const test = () => { }; // Settings: {"jsdoc":{"contexts":["ArrowFunctionExpression"]}} // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true}] // Message: Missing JSDoc comment. export const test = () => { }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[{"context":"ArrowFunctionExpression"}],"publicOnly":true}] // Message: Missing JSDoc comment. export let test = class { }; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ClassExpression":true}}] // Message: Missing JSDoc comment. export default function () {} // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"FunctionDeclaration":true}}] // Message: Missing JSDoc comment. export default () => {} // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"ArrowFunctionExpression":true}}] // Message: Missing JSDoc comment. export default (function () {}) // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. export default class {} // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. function quux (foo) { } // Message: Missing JSDoc comment. function quux (foo) { } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":true}] // Message: Missing JSDoc comment. function quux (foo) { } // Settings: {"jsdoc":{"minLines":2}} // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":true}] // Message: Missing JSDoc comment. function myFunction() {} // Message: Missing JSDoc comment. /** * Description for A. */ class A { constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. class A { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. class A extends B { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export class A extends B { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export default class A extends B { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. var myFunction = () => {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true}}] // Message: Missing JSDoc comment. var myFunction = () => () => {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true}}] // Message: Missing JSDoc comment. var foo = function() {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. const foo = {bar() {}} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. var foo = {bar: function() {}} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. function foo (abc) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":false}] // Message: Missing JSDoc comment. function foo () { return true; } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":false}] // Message: Missing JSDoc comment. module.exports = function quux () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. module.exports = function quux () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. module.exports = { method: function() { } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. module.exports = { test: { test2: function() { } } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. module.exports = { test: { test2: function() { } } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. const test = module.exports = function () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. /** * */ const test = module.exports = function () { } test.prototype.method = function() {} // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. const test = function () { } module.exports = { test: test } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. const test = () => { } module.exports = { test: test } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":true}}] // Message: Missing JSDoc comment. class Test { method() { } } module.exports = Test; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"MethodDefinition":true}}] // Message: Missing JSDoc comment. export default function quux () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. export default function quux () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. function quux () { } export default quux; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. export function test() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. export function test() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. var test = function () { } var test2 = 2; export { test, test2 } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. var test = function () { } export { test as test2 } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. export default class A { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. export default class A { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. var test = function () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"window":true},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. window.test = function () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"window":true},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. function test () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"window":true}}] // Message: Missing JSDoc comment. module.exports = function() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":true,"esm":false,"window":false},"require":{"FunctionExpression":true}}] // Message: Missing JSDoc comment. export function someMethod() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"FunctionDeclaration":true}}] // Message: Missing JSDoc comment. const myObject = { myProp: true }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["Property"]}] // Message: Missing JSDoc comment. /** * Foo interface documentation. */ export interface Foo extends Bar { /** * baz method documentation. */ baz(): void; meow(): void; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSMethodSignature"]}] // Message: Missing JSDoc comment. class MyClass { someProperty: boolean; // Flow type annotation. } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":true,"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. export default class Test { constructor(a) { this.a = a; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":false,"ClassDeclaration":false,"ClassExpression":false,"FunctionDeclaration":false,"FunctionExpression":false,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export default class Test { constructor(a) { this.a = a; } private abc(a) { this.a = a; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition > FunctionExpression"],"publicOnly":true,"require":{"ArrowFunctionExpression":false,"ClassDeclaration":false,"ClassExpression":false,"FunctionDeclaration":false,"FunctionExpression":false,"MethodDefinition":false}}] // Message: Missing JSDoc comment. e = function () { }; // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionDeclaration":false,"FunctionExpression":true}}] // Message: Missing JSDoc comment. /** * */ export class Class { test = 1; foo() { this.test = 2; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionDeclaration":false,"MethodDefinition":true}}] // Message: Missing JSDoc comment. class Dog { eat() { } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionDeclaration":false,"MethodDefinition":true}}] // Message: Missing JSDoc comment. const hello = name => { document.body.textContent = "Hello, " + name + "!"; }; // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true,"FunctionDeclaration":false}}] // Message: Missing JSDoc comment. export const loginSuccessAction = (): BaseActionPayload => ({ type: LOGIN_SUCCESSFUL }); // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true,"FunctionDeclaration":false}}] // Message: Missing JSDoc comment. export type Container = { constants?: ObjByString; enums?: { [key in string]: TypescriptEnum }; helpers?: { [key in string]: AnyFunction }; }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSTypeAliasDeclaration",{"context":"TSPropertySignature","inlineCommentBlock":true}]}] // Message: Missing JSDoc comment. class Foo { constructor() {} bar() {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition[key.name!=\"constructor\"]"],"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. class Example extends React.PureComponent { componentDidMount() {} render() {} someOtherMethod () {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition:not([key.name=\"componentDidMount\"]):not([key.name=\"render\"])"],"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. function foo(arg: boolean): boolean { return arg; } function bar(arg: true): true; function bar(arg: false): false; function bar(arg: boolean): boolean { return arg; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction:not(TSDeclareFunction + TSDeclareFunction)","FunctionDeclaration:not(TSDeclareFunction + FunctionDeclaration)"],"require":{"FunctionDeclaration":false}}] // Message: Missing JSDoc comment. export function foo(arg: boolean): boolean { return arg; } export function bar(arg: true): true; export function bar(arg: false): false; export function bar(arg: boolean): boolean { return arg; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["ExportNamedDeclaration[declaration.type=\"TSDeclareFunction\"]:not(ExportNamedDeclaration[declaration.type=\"TSDeclareFunction\"] + ExportNamedDeclaration[declaration.type=\"TSDeclareFunction\"])","ExportNamedDeclaration[declaration.type=\"FunctionDeclaration\"]:not(ExportNamedDeclaration[declaration.type=\"TSDeclareFunction\"] + ExportNamedDeclaration[declaration.type=\"FunctionDeclaration\"])"],"require":{"FunctionDeclaration":false}}] // Message: Missing JSDoc comment. module.exports.foo = (bar) => { return bar + "biz" } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":false,"require":{"ArrowFunctionExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. class Animal { #name: string; private species: string; public color: string; @SomeAnnotation('optionalParameter') tail: boolean; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["PropertyDefinition"]}] // Message: Missing JSDoc comment. @Entity('users') export class User {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true}}] // Message: Missing JSDoc comment. /** * */ class Foo { constructor() {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyConstructors":false,"require":{"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** * */ class Foo { constructor(notEmpty) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyConstructors":true,"require":{"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** * */ class Foo { constructor() { const notEmpty = true; return notEmpty; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyConstructors":true,"require":{"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** * */ function quux() { } // Settings: {"jsdoc":{"structuredTags":{"see":{"name":false,"required":["name"]}}}} // Message: Cannot add "name" to `require` with the tag's `name` set to `false` class Test { aFunc() {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkConstructors":false,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":false,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. class Test { aFunc = () => {} anotherFunc() {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true,"ClassDeclaration":false,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export enum testEnum { A, B } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSEnumDeclaration"],"publicOnly":true}] // Message: Missing JSDoc comment. export interface Test { aFunc: () => void; aVar: string; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration"],"publicOnly":true}] // Message: Missing JSDoc comment. export type testType = string | number; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSTypeAliasDeclaration"],"publicOnly":true}] // Message: Missing JSDoc comment. export interface Foo { bar: number; baz: string; quux(): void; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSPropertySignature","TSMethodSignature"],"publicOnly":true}] // Message: Missing JSDoc comment. export class MyComponentComponent { @Output() public changed = new EventEmitter(); public test = 'test'; @Input() public value = new EventEmitter(); } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["PropertyDefinition > Decorator[expression.callee.name=\"Input\"]"]}] // Message: Missing JSDoc comment. requestAnimationFrame(draw) function bench() { } // Message: Missing JSDoc comment. class Foo { set aName (val) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkSetters":"no-getter","contexts":["MethodDefinition > FunctionExpression"]}] // Message: Missing JSDoc comment. class Foo { get aName () {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":"no-setter","contexts":["MethodDefinition > FunctionExpression"]}] // Message: Missing JSDoc comment. const obj = { get aName () {}, } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":"no-setter","contexts":["Property > FunctionExpression"]}] // Message: Missing JSDoc comment. function comment () { return "comment"; } // "jsdoc/require-jsdoc": ["error"|"warn", {"enableFixer":true,"fixerMessage":" TODO: add comment"}] // Message: Missing JSDoc comment. function comment () { return "comment"; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["any",{"context":"FunctionDeclaration","inlineCommentBlock":true}],"fixerMessage":"TODO: add comment "}] // Message: Missing JSDoc comment. function comment () { return "comment"; } // "jsdoc/require-jsdoc": ["error"|"warn", {"enableFixer":false,"fixerMessage":" TODO: add comment"}] // Message: Missing JSDoc comment. export class InovaAutoCompleteComponent { public disabled = false; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["PropertyDefinition"],"publicOnly":true}] // Message: Missing JSDoc comment. export default (arg) => arg; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export function outer() { function inner() { console.log('foo'); } inner(); } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export const outer = () => { const inner = () => { console.log('foo'); }; inner(); }; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** * */ export class InovaAutoCompleteComponent { public disabled = false; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["PropertyDefinition"],"publicOnly":true}] // Message: Missing JSDoc comment. /** * Some comment. */ export class Component { public foo?: number; } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkConstructors":false,"contexts":["PropertyDefinition"],"publicOnly":true}] // Message: Missing JSDoc comment. class Utility { /** * */ mthd() { return false; } } module.exports = Utility; // "jsdoc/require-jsdoc": ["error"|"warn", {"enableFixer":false,"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** * */ module.exports = class Utility { mthd() { return false; } }; // "jsdoc/require-jsdoc": ["error"|"warn", {"enableFixer":false,"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. function quux () { return 3; } function b () {} // "jsdoc/require-jsdoc": ["error"|"warn", {"minLineCount":2}] // Message: Missing JSDoc comment. function quux () { return 3; } var a = {}; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[{"context":"FunctionDeclaration","minLineCount":2},{"context":"VariableDeclaration","minLineCount":2}],"require":{"FunctionDeclaration":false}}] // Message: Missing JSDoc comment. function quux () { return 3; } var a = { b: 1, c: 2 }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[{"context":"FunctionDeclaration","minLineCount":4},{"context":"VariableDeclaration","minLineCount":2}],"require":{"FunctionDeclaration":false}}] // Message: Missing JSDoc comment. class A { setId(newId: number): void { this.id = id; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[{"context":"MethodDefinition","minLineCount":3}],"require":{"ClassDeclaration":false,"FunctionExpression":false,"MethodDefinition":false}}] // Message: Missing JSDoc comment. export class MyClass { public myPublicProperty: number = 1; /* ^ Missing JSDoc comment. eslint(jsdoc/require-jsdoc) - expected ✅ */ private myPrivateProp: number = -1; /* ^ Missing JSDoc comment. eslint(jsdoc/require-jsdoc) - unexpected ❌ */ // ... } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["PropertyDefinition"],"publicOnly":true}] // Message: Missing JSDoc comment. export const Comp = observer(() => <>Hello); // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["CallExpression[callee.name=\"observer\"]"],"enableFixer":false,"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. /** * Command options for the login command */ export type LoginOptions = CmdOptions<{ username?: string; password?: string; }>; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSTypeAliasDeclaration","TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] // Message: Missing JSDoc comment. type Props = { variant: string } export type { Props as ComponentProps }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["VariableDeclaration","TSTypeAliasDeclaration","TSPropertySignature","TSInterfaceDeclaration","TSMethodSignature","TSEnumDeclaration"],"enableFixer":true,"publicOnly":{"esm":true},"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":true,"MethodDefinition":true}}] // Message: Missing JSDoc comment. export interface A { a: string; } export class B implements A, B { a = 'abc'; public f(): void { // } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition"]}] // Message: Missing JSDoc comment. /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; /** * Test function without param. */ function myFunction(): void; function myFunction(foo?: string) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"skipInterveningOverloadedDeclarations":false}] // Message: Missing JSDoc comment. /** * Test function without param. */ function myFunction(): void; /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; function myFunction(foo?: string) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"skipInterveningOverloadedDeclarations":false}] // Message: Missing JSDoc comment. /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; function myFunction(): void; /** * Function implementation * @param foo */ function myFunction(foo?: string) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction"],"exemptOverloadedImplementations":false,"skipInterveningOverloadedDeclarations":false}] // Message: Missing JSDoc comment. /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; function myFunction(): void; function myFunction(foo?: string) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction"],"exemptOverloadedImplementations":true,"skipInterveningOverloadedDeclarations":false}] // Message: Missing JSDoc comment. const foo = autolog( function foo() { log.debug('inside foo', 'this is a test helper function') }, { withGovernance: true, withProfiling: true }, ) // "jsdoc/require-jsdoc": ["error"|"warn", {"checkAllFunctionExpressions":true,"contexts":["FunctionExpression"],"require":{"FunctionExpression":false}}] // Message: Missing JSDoc comment. ```` ## Passing examples The following patterns are not considered problems: ````ts interface FooBar { fooBar: string; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] /** This is comment */ interface FooBar { fooBar: string; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] /** This is comment */ export class Foo { someMethod() { interface FooBar { fooBar: string; } } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] /** This is comment */ function someFunction() { interface FooBar { fooBar: string; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] /** This is comment */ export function foo() { interface bar { fooBar: string; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration","TSMethodSignature","TSPropertySignature"],"publicOnly":{"ancestorsOnly":true}}] /** * */ var array = [1,2,3]; array.forEach(function() {}); /** * @class MyClass **/ function MyClass() {} /** Function doing something */ function myFunction() {} /** Function doing something */ var myFunction = function() {}; /** Function doing something */ Object.myFunction = function () {}; var obj = { /** * Function doing something **/ myFunction: function () {} }; /** @func myFunction */ function myFunction() {} /** @method myFunction */ function myFunction() {} /** @function myFunction */ function myFunction() {} /** @func myFunction */ var myFunction = function () {} /** @method myFunction */ var myFunction = function () {} /** @function myFunction */ var myFunction = function () {} /** @func myFunction */ Object.myFunction = function() {} /** @method myFunction */ Object.myFunction = function() {} /** @function myFunction */ Object.myFunction = function() {} (function(){})(); var object = { /** * @func myFunction - Some function */ myFunction: function() {} } var object = { /** * @method myFunction - Some function */ myFunction: function() {} } var object = { /** * @function myFunction - Some function */ myFunction: function() {} } var array = [1,2,3]; array.filter(function() {}); Object.keys(this.options.rules || {}).forEach(function(name) {}.bind(this)); var object = { name: 'key'}; Object.keys(object).forEach(function() {}) /** * @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"maxLines":2,"minLines":0}} /** * @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"maxLines":3,"minLines":0}} /** @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"maxLines":0,"minLines":0}} /** * @func myFunction */ function myFunction() { } // Settings: {"jsdoc":{"maxLines":3,"minLines":2}} function myFunction() {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"FunctionDeclaration":false,"MethodDefinition":true}}] var myFunction = function() {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"FunctionDeclaration":false,"MethodDefinition":true}}] /** * Description for A. */ class A { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] /** * Description for A. */ class App extends Component { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] /** * Description for A. */ export default class App extends Component { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] /** * Description for A. */ export class App extends Component { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true,"MethodDefinition":true}}] class A { constructor(xs) { this.a = xs; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":false,"MethodDefinition":false}}] /** * Function doing something */ var myFunction = () => {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true}}] /** * Function doing something */ var myFunction = function () {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true}}] /** * Function doing something */ var myFunction = () => {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":false}}] /** Function doing something */ var myFunction = () => () => {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true}}] setTimeout(() => {}, 10); // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":true}}] /** JSDoc Block */ var foo = function() {} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] const foo = {/** JSDoc Block */ bar() {}} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] var foo = {/** JSDoc Block */ bar: function() {}} // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] var foo = { [function() {}]: 1 }; // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"FunctionExpression":true}}] function foo () {} // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":true}] function foo () { return; } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":true}] const test = {}; /** * test */ test.method = function () { } module.exports = { prop: { prop2: test.method } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ function test() { } module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ test = function() { } module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":true,"esm":false,"window":false},"require":{"FunctionExpression":true}}] /** * */ test = function() { } exports.someMethod = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"FunctionExpression":true}}] /** * */ const test = () => { } module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":true}}] const test = () => { } module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"ArrowFunctionExpression":true}}] /** * */ window.test = function() { } module.exports = { prop: window } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] test = function() { } /** * */ test = function() { } module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] test = function() { } test = 2; module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ function test() { } /** * */ test.prototype.method = function() { } module.exports = { prop: { prop2: test } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] class Test { /** * Test */ method() { } } module.exports = Test; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"MethodDefinition":true}}] /** * */ export default function quux () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ export default function quux () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] /** * */ function quux () { } export default quux; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] function quux () { } export default quux; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] /** * */ export function test() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ export function test() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"FunctionExpression":true}}] /** * */ var test = function () { } var test2 = 2; export { test, test2 } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ var test = function () { } export { test as test2 } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * */ export default class A { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true},"require":{"ClassDeclaration":true}}] /** * */ var test = function () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"window":true},"require":{"FunctionExpression":true}}] let test = function () { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"window":true},"require":{"FunctionExpression":true}}] let test = class { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ClassExpression":false}}] /** * */ let test = class { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ClassExpression":true}}] export function someMethod() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":true,"esm":false,"window":false},"require":{"FunctionDeclaration":true}}] exports.someMethod = function() { } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":{"cjs":false,"esm":true,"window":false},"require":{"FunctionExpression":true}}] const myObject = { myProp: true }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[]}] function bear() {} /** * */ function quux () { } export default quux; // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"FunctionExpression":true}}] /** * This example interface is great! */ export interface Example { /** * My super test string! */ test: string } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration"]}] /** * This example interface is great! */ interface Example { /** * My super test string! */ test: string } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSInterfaceDeclaration"]}] /** * This example type is great! */ export type Example = { /** * My super test string! */ test: string }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSTypeAliasDeclaration"]}] /** * This example type is great! */ type Example = { /** * My super test string! */ test: string }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSTypeAliasDeclaration"]}] /** * This example enum is great! */ export enum Example { /** * My super test enum! */ test = 123 } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSEnumDeclaration"]}] /** * This example enum is great! */ enum Example { /** * My super test enum! */ test = 123 } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSEnumDeclaration"]}] const foo = {...{}}; function bar() {} // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":false,"publicOnly":true,"require":{"ArrowFunctionExpression":true,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":false,"MethodDefinition":true}}] /** * Class documentation */ @logged export default class Foo { // .... } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyFunctions":false,"require":{"ClassDeclaration":true}}] const a = {}; const b = { ...a }; export default b; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["ObjectExpression"],"exemptEmptyFunctions":false,"publicOnly":true}] /** * Foo interface documentation. */ export interface Foo extends Bar { /** * baz method documentation. */ baz(): void; /** * meow method documentation. */ meow(): void; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSMethodSignature"]}] export default class Test { private abc(a) { this.a = a; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition > FunctionExpression"],"publicOnly":true,"require":{"ArrowFunctionExpression":false,"ClassDeclaration":false,"ClassExpression":false,"FunctionDeclaration":false,"FunctionExpression":false,"MethodDefinition":false}}] /** * Basic application controller. */ @Controller() export class AppController { /** * Returns the application information. * * @returns ... */ @Get('/info') public getInfo(): string { return 'OK'; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":false,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":false,"MethodDefinition":true}}] /** * Entity to represent a user in the system. */ @Entity('users') export class User { } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":false,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":false,"MethodDefinition":true}}] /** * Entity to represent a user in the system. */ @Entity('users', getVal()) export class User { } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ArrowFunctionExpression":false,"ClassDeclaration":true,"ClassExpression":true,"FunctionDeclaration":true,"FunctionExpression":false,"MethodDefinition":true}}] /** * */ class Foo { constructor() {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptEmptyConstructors":true,"require":{"MethodDefinition":true}}] /** * */ class Foo { constructor() {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkConstructors":false,"require":{"MethodDefinition":true}}] class Foo { get aName () {} set aName (val) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":"no-setter","checkSetters":false,"contexts":["MethodDefinition > FunctionExpression"]}] const obj = { get aName () {}, set aName (val) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":"no-setter","checkSetters":false,"contexts":["Property > FunctionExpression"]}] class Foo { set aName (val) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkSetters":false,"contexts":["MethodDefinition > FunctionExpression"]}] class Foo { get aName () {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":false,"contexts":["MethodDefinition > FunctionExpression"]}] class Foo { /** * */ set aName (val) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkSetters":"no-getter","contexts":["MethodDefinition > FunctionExpression"]}] class Foo { /** * */ get aName () {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":"no-setter","contexts":["MethodDefinition > FunctionExpression"]}] class Foo { get aName () {} set aName (val) {} } // "jsdoc/require-jsdoc": ["error"|"warn", {"checkGetters":false,"checkSetters":"no-getter","contexts":["MethodDefinition > FunctionExpression"]}] class Base { constructor() { } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition"],"exemptEmptyConstructors":true}] /** * This is a text. */ export function a(); // Reports an error // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction"],"require":{"FunctionDeclaration":true}}] /** * Foo */ export function foo(): void { function bar(): void { console.log('bar'); } console.log('foo'); } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true}] const foo = { bar: () => { // ... } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[":not(Property) > ArrowFunctionExpression"],"require":{"ArrowFunctionExpression":false,"ClassDeclaration":true,"ClassExpression":true}}] /** Defines the current user's settings. */ @Injectable({ providedIn: 'root', }) @State> ({ name: 'userSettings', defaults: { isDev: !environment.production, }, }) export class UserSettingsState { } // "jsdoc/require-jsdoc": ["error"|"warn", {"require":{"ClassDeclaration":true}}] /** * Entity to represent a user in the system. */ @Entity('users') export class User { } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["Decorator"],"require":{"FunctionDeclaration":false}}] function quux () { return 3; } function b () {} // "jsdoc/require-jsdoc": ["error"|"warn", {"minLineCount":4}] function quux () { return 3; } var a = { b: 1, c: 2 }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["ClassDeclaration",{"context":"FunctionDeclaration","minLineCount":4},{"context":"VariableDeclaration","minLineCount":5}],"require":{"FunctionDeclaration":false}}] class A { setId(newId: number): void { this.id = id; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":[{"context":"MethodDefinition","minLineCount":4}],"require":{"ClassDeclaration":false,"FunctionExpression":false,"MethodDefinition":false}}] export default class Test { private abc(a) { this.a = a; } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ArrowFunctionExpression":false,"ClassDeclaration":false,"ClassExpression":false,"FunctionDeclaration":false,"FunctionExpression":false,"MethodDefinition":true}}] export default { created() { this.getData(); }, beforeUpdate() {}, watch: { someValue(val) {} }, computed: { loaded() {}, selection() {} }, methods: { getData(id) {} } }; // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["ExportDefaultDeclaration > ObjectExpression > Property[key.name!=/^(created|beforeUpdate)$/] > FunctionExpression","ExportDefaultDeclaration > ObjectExpression > Property[key.name!=/^(watch|computed|methods)$/] > ObjectExpression > Property > FunctionExpression"]}] export class MyClass { #myPrivateMethod(): void { } #myPrivateProp = 5; } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["PropertyDefinition"],"publicOnly":true,"require":{"MethodDefinition":true}}] class Abc { static { this.x = '2' } } // "jsdoc/require-jsdoc": ["error"|"warn", {"publicOnly":true,"require":{"ClassDeclaration":true}}] /** * Array map function with overload for NonEmptyArray * @example * const data = [{value: 'value'}] as const; * const result1: NonEmptyReadonlyArray<'value'> = arrayMap(data, (value) => value.value); // pick type from data * const result2: NonEmptyReadonlyArray<'value'> = arrayMap<'value', typeof data>(data, (value) => value.value); // enforce output type * @template Target - The type of the array to map to * @template Source - The type of the array to map from * @param {Source} data - The array to map * @param {MapCallback} callback - Callback function to map data from the array * @returns {AnyArrayType} Mapped array * @since v0.2.0 */ export function arrayMap | NonEmptyReadonlyArray>( data: Source, callback: MapCallback, ): NonEmptyArray; export function arrayMap>(data: Source, callback: MapCallback): Array; export function arrayMap(data: Source, callback: MapCallback): AnyArrayType { return data.map(callback); } // "jsdoc/require-jsdoc": ["error"|"warn", {"skipInterveningOverloadedDeclarations":true}] /** * Array map function with overload for NonEmptyArray * @example * const data = [{value: 'value'}] as const; * const result1: NonEmptyReadonlyArray<'value'> = arrayMap(data, (value) => value.value); // pick type from data * const result2: NonEmptyReadonlyArray<'value'> = arrayMap<'value', typeof data>(data, (value) => value.value); // enforce output type * @template Target - The type of the array to map to * @template Source - The type of the array to map from * @param {Source} data - The array to map * @param {MapCallback} callback - Callback function to map data from the array * @returns {AnyArrayType} Mapped array * @since v0.2.0 */ export function arrayMap | NonEmptyReadonlyArray>( data: Source, callback: MapCallback, ): NonEmptyArray; export function arrayMap>(data: Source, callback: MapCallback): Array; export function arrayMap(data: Source, callback: MapCallback): AnyArrayType { return data.map(callback); } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction"],"exemptOverloadedImplementations":false,"skipInterveningOverloadedDeclarations":true}] export interface A { a: string; /** * Documentation. */ f(): void; } export class B implements A { a = 'abc'; public f(): void { // } } // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["MethodDefinition"]}] /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; /** * Test function without param. */ function myFunction(): void; function myFunction(foo?: string) {} /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; /** * Test function without param. */ function myFunction(): void; function myFunction(foo?: string) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction"],"exemptOverloadedImplementations":true,"skipInterveningOverloadedDeclarations":false}] /** * Test function with param. * @param foo - Test param. */ export function myFunction(foo: string): void; /** * Test function without param. */ export function myFunction(): void; export function myFunction(foo?: string) {} // "jsdoc/require-jsdoc": ["error"|"warn", {"contexts":["TSDeclareFunction"],"exemptOverloadedImplementations":true,"skipInterveningOverloadedDeclarations":false}] /** * */ const quux = () => { /** * */ function myFunction(foo?: string) {} }; // "jsdoc/require-jsdoc": ["error"|"warn", {"exemptOverloadedImplementations":true,"require":{"ArrowFunctionExpression":true}}] ```` --- # require-next-description Requires a description for (non-standard) `@next` tags. ||| |---|---| |Context|everywhere| |Tags|`next`| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @next {SomeType} */ // Message: @next should have a description ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @next {SomeType} Has a description */ ```` --- # require-next-type Requires a type on the (non-standard) `@next` tag. See the `jsdoc/require-yields` rule for details on this tag. ||| |---|---| |Context|everywhere| |Tags|`next`| |Recommended|true| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @next */ // Message: @next should have a type ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @next {SomeType} */ ```` --- # require-param-description * [Options](#user-content-require-param-description-options) * [`contexts`](#user-content-require-param-description-options-contexts) * [`defaultDestructuredRootDescription`](#user-content-require-param-description-options-defaultdestructuredrootdescription) * [`setDefaultDestructuredRootDescription`](#user-content-require-param-description-options-setdefaultdestructuredrootdescription) * [Context and settings](#user-content-require-param-description-context-and-settings) * [Failing examples](#user-content-require-param-description-failing-examples) * [Passing examples](#user-content-require-param-description-passing-examples) Requires that each `@param` tag has a `description` value. Will exempt destructured roots and their children if `settings.exemptDestructuredRootsFromChecks` is set to `true` (e.g., `@param {object} props` will be exempted from requiring a description given `function someFunc ({child1, child2})`). ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### defaultDestructuredRootDescription The description string to set by default for destructured roots. Defaults to "The root object". ### setDefaultDestructuredRootDescription Whether to set a default destructured root description. For example, you may wish to avoid manually having to set the description for a `@param` corresponding to a destructured root object as it should always be the same type of object. Uses `defaultDestructuredRootDescription` for the description string. Defaults to `false`. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`param`| |Aliases|`arg`, `argument`| |Recommended|true| |Options|`contexts`, `defaultDestructuredRootDescription`, `setDefaultDestructuredRootDescription`| |Settings|`exemptDestructuredRootsFromChecks`| ## Failing examples The following patterns are considered problems: ````ts /** * @param foo */ function quux (foo) { } // Message: Missing JSDoc @param "foo" description. /** * @param foo */ function quux (foo) { } // "jsdoc/require-param-description": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @param "foo" description. /** * @function * @param foo */ // "jsdoc/require-param-description": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @param "foo" description. /** * @callback * @param foo */ // "jsdoc/require-param-description": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @param "foo" description. /** * @arg foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} // Message: Missing JSDoc @arg "foo" description. /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":false}}} // Message: Unexpected tag `@param` /** * @param foo */ function quux (foo) { } // "jsdoc/require-param-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag:not([name=props]))","context":"FunctionDeclaration"}]}] // Message: Missing JSDoc @param "foo" description. /** * @param {number} foo Foo description * @param {object} root * @param {boolean} baz Baz description */ function quux (foo, {bar}, baz) { } // "jsdoc/require-param-description": ["error"|"warn", {"setDefaultDestructuredRootDescription":true}] // Message: Missing root description for @param. /** * @param {number} foo Foo description * @param {object} root * @param {boolean} baz Baz description */ function quux (foo, {bar}, baz) { } // "jsdoc/require-param-description": ["error"|"warn", {"defaultDestructuredRootDescription":"Root description","setDefaultDestructuredRootDescription":true}] // Message: Missing root description for @param. /** * @param {number} foo Foo description * @param {object} root * @param {boolean} baz Baz description */ function quux (foo, {bar}, baz) { } // "jsdoc/require-param-description": ["error"|"warn", {"setDefaultDestructuredRootDescription":false}] // Message: Missing JSDoc @param "root" description. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ function quux (foo) { } /** * @param foo Foo. */ function quux (foo) { } /** * @param foo Foo. */ function quux (foo) { } // "jsdoc/require-param-description": ["error"|"warn", {"contexts":["any"]}] /** * @function * @param foo */ /** * @callback * @param foo */ /** * @param props */ function quux (props) { } // "jsdoc/require-param-description": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag:not([name=props]))","context":"FunctionDeclaration"}]}] /** * @param {number} foo Foo description * @param {object} root * @param {boolean} baz Baz description */ function quux (foo, {bar}, baz) { } // Settings: {"jsdoc":{"exemptDestructuredRootsFromChecks":true}} /** * @param {number} foo Foo description * @param {object} root * @param {object} root.bar */ function quux (foo, {bar: {baz}}) { } // Settings: {"jsdoc":{"exemptDestructuredRootsFromChecks":true}} ```` --- # require-param-name * [Options](#user-content-require-param-name-options) * [`contexts`](#user-content-require-param-name-options-contexts) * [Context and settings](#user-content-require-param-name-context-and-settings) * [Failing examples](#user-content-require-param-name-failing-examples) * [Passing examples](#user-content-require-param-name-passing-examples) Requires that all `@param` tags have names. > The `@param` tag requires you to specify the name of the parameter you are documenting. You can also include the parameter's type, enclosed in curly brackets, and a description of the parameter. > > [JSDoc](https://jsdoc.app/tags-param.html#overview) ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`param`| |Aliases|`arg`, `argument`| |Recommended|true| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * @param */ function quux (foo) { } // Message: There must be an identifier after @param type. /** * @param {string} */ function quux (foo) { } // Message: There must be an identifier after @param tag. /** * @param {string} */ function quux (foo) { } // "jsdoc/require-param-name": ["error"|"warn", {"contexts":["any"]}] // Message: There must be an identifier after @param tag. /** * @function * @param {string} */ // "jsdoc/require-param-name": ["error"|"warn", {"contexts":["any"]}] // Message: There must be an identifier after @param tag. /** * @callback * @param {string} */ // "jsdoc/require-param-name": ["error"|"warn", {"contexts":["any"]}] // Message: There must be an identifier after @param tag. /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":false}}} // Message: Unexpected tag `@param` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param foo */ function quux (foo) { } /** * @param foo */ function quux (foo) { } // "jsdoc/require-param-name": ["error"|"warn", {"contexts":["any"]}] /** * @param {string} foo */ function quux (foo) { } /** * @function * @param */ /** * @callback * @param */ /** * @param {Function} [processor=data => data] A function to run */ function processData(processor) { return processor(data) } /** Example with multi-line param type. * * @param {function( * number * )} cb Callback. */ function example(cb) { cb(42); } ```` --- # require-param-type * [Options](#user-content-require-param-type-options) * [`contexts`](#user-content-require-param-type-options-contexts) * [`defaultDestructuredRootType`](#user-content-require-param-type-options-defaultdestructuredroottype) * [`setDefaultDestructuredRootType`](#user-content-require-param-type-options-setdefaultdestructuredroottype) * [Context and settings](#user-content-require-param-type-context-and-settings) * [Failing examples](#user-content-require-param-type-failing-examples) * [Passing examples](#user-content-require-param-type-passing-examples) Requires that each `@param` tag has a `type` value (within curly brackets). Will exempt destructured roots and their children if `settings.exemptDestructuredRootsFromChecks` is set to `true` (e.g., `@param props` will be exempted from requiring a type given `function someFunc ({child1, child2})`). ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### defaultDestructuredRootType The type string to set by default for destructured roots. Defaults to "object". ### setDefaultDestructuredRootType Whether to set a default destructured root type. For example, you may wish to avoid manually having to set the type for a `@param` corresponding to a destructured root object as it is always going to be an object. Uses `defaultDestructuredRootType` for the type string. Defaults to `false`. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`param`| |Aliases|`arg`, `argument`| |Recommended|true| |Options|`contexts`, `defaultDestructuredRootType`, `setDefaultDestructuredRootType`| |Settings|`exemptDestructuredRootsFromChecks`| ## Failing examples The following patterns are considered problems: ````ts /** * @param foo */ function quux (foo) { } // Message: Missing JSDoc @param "foo" type. /** * @param {a xxx */ function quux () { } // Message: Missing JSDoc @param "" type. /** * @param foo */ function quux (foo) { } // "jsdoc/require-param-type": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @param "foo" type. /** * @function * @param foo */ // "jsdoc/require-param-type": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @param "foo" type. /** * @callback * @param foo */ // "jsdoc/require-param-type": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @param "foo" type. /** * @arg foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} // Message: Missing JSDoc @arg "foo" type. /** * @param foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":false}}} // Message: Unexpected tag `@param` /** * @param {number} foo * @param root * @param {boolean} baz */ function quux (foo, {bar}, baz) { } // "jsdoc/require-param-type": ["error"|"warn", {"setDefaultDestructuredRootType":true}] // Message: Missing root type for @param. /** * @param {number} foo * @param root * @param {boolean} baz */ function quux (foo, {bar}, baz) { } // "jsdoc/require-param-type": ["error"|"warn", {"defaultDestructuredRootType":"Object","setDefaultDestructuredRootType":true}] // Message: Missing root type for @param. /** * @param {number} foo * @param root * @param {boolean} baz */ function quux (foo, {bar}, baz) { } // "jsdoc/require-param-type": ["error"|"warn", {"setDefaultDestructuredRootType":false}] // Message: Missing JSDoc @param "root" type. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ function quux (foo) { } /** * @param {number} foo */ function quux (foo) { } /** * @param {number} foo */ function quux (foo) { } // "jsdoc/require-param-type": ["error"|"warn", {"contexts":["any"]}] /** * @function * @param foo */ /** * @callback * @param foo */ /** * @param {number} foo * @param root * @param {boolean} baz */ function quux (foo, {bar}, baz) { } // Settings: {"jsdoc":{"exemptDestructuredRootsFromChecks":true}} /** * @param {number} foo * @param root * @param root.bar */ function quux (foo, {bar: {baz}}) { } // Settings: {"jsdoc":{"exemptDestructuredRootsFromChecks":true}} ```` --- # require-param * [Fixer](#user-content-require-param-fixer) * [Destructured object and array naming](#user-content-require-param-fixer-destructured-object-and-array-naming) * [Missing root fixing](#user-content-require-param-fixer-missing-root-fixing) * [Rest Element (`RestElement`) insertions](#user-content-require-param-fixer-rest-element-restelement-insertions) * [Object Rest Property insertions](#user-content-require-param-fixer-object-rest-property-insertions) * [Options](#user-content-require-param-options) * [`autoIncrementBase`](#user-content-require-param-options-autoincrementbase) * [`checkConstructors`](#user-content-require-param-options-checkconstructors) * [`checkDestructured`](#user-content-require-param-options-checkdestructured) * [`checkDestructuredRoots`](#user-content-require-param-options-checkdestructuredroots) * [`checkGetters`](#user-content-require-param-options-checkgetters) * [`checkRestProperty`](#user-content-require-param-options-checkrestproperty) * [`checkSetters`](#user-content-require-param-options-checksetters) * [`checkTypesPattern`](#user-content-require-param-options-checktypespattern) * [`contexts`](#user-content-require-param-options-contexts) * [`enableFixer`](#user-content-require-param-options-enablefixer) * [`enableRestElementFixer`](#user-content-require-param-options-enablerestelementfixer) * [`enableRootFixer`](#user-content-require-param-options-enablerootfixer) * [`exemptedBy`](#user-content-require-param-options-exemptedby) * [`ignoreWhenAllParamsMissing`](#user-content-require-param-options-ignorewhenallparamsmissing) * [`interfaceExemptsParamsCheck`](#user-content-require-param-options-interfaceexemptsparamscheck) * [`unnamedRootBase`](#user-content-require-param-options-unnamedrootbase) * [`useDefaultObjectProperties`](#user-content-require-param-options-usedefaultobjectproperties) * [Context and settings](#user-content-require-param-context-and-settings) * [Failing examples](#user-content-require-param-failing-examples) * [Passing examples](#user-content-require-param-passing-examples) Requires that all function parameters are documented. ## Fixer Adds `@param ` for each tag present in the function signature but missing in the jsdoc. Can be disabled by setting the `enableFixer` option to `false`. ### Destructured object and array naming When the fixer is applied to destructured objects, only the input name is used. So for: ```js /** * @param cfg */ function quux ({foo: bar, baz: bax = 5}) { } ``` ...the fixed JSDoc will be: ```js /** * @param cfg * @param cfg.foo * @param cfg.baz */ ``` This is because the input to the function is the relevant item for understanding the function's input, not how the variable is renamed for internal use (the signature itself documents that). For destructured arrays, the input name is merely the array index. So for: ```js /** * @param cfg */ function quux ([foo, bar]) { } ``` ..the fixed JSDoc will be: ```js /** * @param cfg * @param cfg."0" * @param cfg."1" */ ``` ### Missing root fixing Note that unless `enableRootFixer` (or `enableFixer`) is set to `false`, missing roots will be added and auto-incremented. The default behavior is for "root" to be auto-inserted for missing roots, followed by a 0-based auto-incrementing number. So for: ```js function quux ({foo}, {bar}, {baz}) { } ``` ...the default JSDoc that would be added if the fixer is enabled would be: ```js /** * @param root0 * @param root0.foo * @param root1 * @param root1.bar * @param root2 * @param root2.baz */ ``` The name of "root" can be configured with `unnamedRootBase` (which also allows cycling through a list of multiple root names before there is need for any numeric component). And one can have the count begin at another number (e.g., `1`) by changing `autoIncrementBase` from the default of `0`. ### Rest Element (RestElement) insertions The fixer will automatically report/insert [JSDoc repeatable parameters](https://jsdoc.app/tags-param.html#multiple-types-and-repeatable-parameters) if missing. ```js /** * @param {GenericArray} cfg * @param {number} cfg."0" */ function baar ([a, ...extra]) { // } ``` ...becomes: ```js /** * @param {GenericArray} cfg * @param {number} cfg."0" * @param {...any} cfg."1" */ function baar ([a, ...extra]) { // } ``` Note that the type `any` is included since we don't know of any specific type to use. To disable such rest element insertions, set `enableRestElementFixer` to `false`. Note too that the following will be reported even though there is an item corresponding to `extra`: ```js /** * @param {GenericArray} cfg * @param {number} cfg."0" * @param {any} cfg."1" */ function baar ([a, ...extra]) { // } ``` ...because it does not use the `...` syntax in the type. ### Object Rest Property insertions If the `checkRestProperty` option is set to `true` (`false` by default), missing rest properties will be reported with documentation auto-inserted: ```js /** * @param cfg * @param cfg.num */ function quux ({num, ...extra}) { } ``` ...becomes: ```js /** * @param cfg * @param cfg.num * @param cfg.extra */ function quux ({num, ...extra}) { } ``` You may wish to manually note in your JSDoc for `extra` that this is a rest property, however, as jsdoc [does not appear](https://github.com/jsdoc/jsdoc/issues/1773) to currently support syntax or output to distinguish rest properties from other properties, so in looking at the docs alone without looking at the function signature, it may appear that there is an actual property named `extra`. ## Options A single options object has the following properties. ### autoIncrementBase Numeric to indicate the number at which to begin auto-incrementing roots. Defaults to `0`. ### checkConstructors A value indicating whether `constructor`s should be checked. Defaults to `true`. ### checkDestructured Whether to require destructured properties. Defaults to `true`. ### checkDestructuredRoots Whether to check the existence of a corresponding `@param` for root objects of destructured properties (e.g., that for `function ({a, b}) {}`, that there is something like `@param myRootObj` defined that can correspond to the `{a, b}` object parameter). If `checkDestructuredRoots` is `false`, `checkDestructured` will also be implied to be `false` (i.e., the inside of the roots will not be checked either, e.g., it will also not complain if `a` or `b` do not have their own documentation). Defaults to `true`. ### checkGetters A value indicating whether getters should be checked. Defaults to `false`. ### checkRestProperty If set to `true`, will report (and add fixer insertions) for missing rest properties. Defaults to `false`. If set to `true`, note that you can still document the subproperties of the rest property using other jsdoc features, e.g., `@typedef`: ```js /** * @typedef ExtraOptions * @property innerProp1 * @property innerProp2 */ /** * @param cfg * @param cfg.num * @param {ExtraOptions} extra */ function quux ({num, ...extra}) { } ``` Setting this option to `false` (the default) may be useful in cases where you already have separate `@param` definitions for each of the properties within the rest property. For example, with the option disabled, this will not give an error despite `extra` not having any definition: ```js /** * @param cfg * @param cfg.num */ function quux ({num, ...extra}) { } ``` Nor will this: ```js /** * @param cfg * @param cfg.num * @param cfg.innerProp1 * @param cfg.innerProp2 */ function quux ({num, ...extra}) { } ``` ### checkSetters A value indicating whether setters should be checked. Defaults to `false`. ### checkTypesPattern When one specifies a type, unless it is of a generic type, like `object` or `array`, it may be considered unnecessary to have that object's destructured components required, especially where generated docs will link back to the specified type. For example: ```js /** * @param {SVGRect} bbox - a SVGRect */ export const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; ``` By default `checkTypesPattern` is set to `/^(?:[oO]bject|[aA]rray|PlainObject|Generic(?:Object|Array))$/v`, meaning that destructuring will be required only if the type of the `@param` (the text between curly brackets) is a match for "Object" or "Array" (with or without initial caps), "PlainObject", or "GenericObject", "GenericArray" (or if no type is present). So in the above example, the lack of a match will mean that no complaint will be given about the undocumented destructured parameters. Note that the `/` delimiters are optional, but necessary to add flags. Defaults to using (only) the `v` flag, so to add your own flags, encapsulate your expression as a string, but like a literal, e.g., `/^object$/vi`. You could set this regular expression to a more expansive list, or you could restrict it such that even types matching those strings would not need destructuring. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). May be useful for adding such as `TSMethodSignature` in TypeScript or restricting the contexts which are checked. See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ### enableFixer Whether to enable the fixer. Defaults to `true`. ### enableRestElementFixer Whether to enable the rest element fixer. The fixer will automatically report/insert [JSDoc repeatable parameters](https://jsdoc.app/tags-param.html#multiple-types-and-repeatable-parameters) if missing. ```js /** * @param {GenericArray} cfg * @param {number} cfg."0" */ function baar ([a, ...extra]) { // } ``` ...becomes: ```js /** * @param {GenericArray} cfg * @param {number} cfg."0" * @param {...any} cfg."1" */ function baar ([a, ...extra]) { // } ``` Note that the type `any` is included since we don't know of any specific type to use. Defaults to `true`. ### enableRootFixer Whether to enable the auto-adding of incrementing roots. The default behavior of `true` is for "root" to be auto-inserted for missing roots, followed by a 0-based auto-incrementing number. So for: ```js function quux ({foo}, {bar}, {baz}) { } ``` ...the default JSDoc that would be added if the fixer is enabled would be: ```js /** * @param root0 * @param root0.foo * @param root1 * @param root1.bar * @param root2 * @param root2.baz */ ``` Has no effect if `enableFixer` is set to `false`. ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@param`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ### ignoreWhenAllParamsMissing Set to `true` to ignore reporting when all params are missing. Defaults to `false`. ### interfaceExemptsParamsCheck Set if you wish TypeScript interfaces to exempt checks for the existence of `@param`'s. Will check for a type defining the function itself (on a variable declaration) or if there is a single destructured object with a type. Defaults to `false`. ### unnamedRootBase An array of root names to use in the fixer when roots are missing. Defaults to `['root']`. Note that only when all items in the array besides the last are exhausted will auto-incrementing occur. So, with `unnamedRootBase: ['arg', 'config']`, the following: ```js function quux ({foo}, [bar], {baz}) { } ``` ...will get the following JSDoc block added: ```js /** * @param arg * @param arg.foo * @param config0 * @param config0."0" (`bar`) * @param config1 * @param config1.baz */ ``` ### useDefaultObjectProperties Set to `true` if you wish to expect documentation of properties on objects supplied as default values. Defaults to `false`. ## Context and settings | | | | -------- | ----------------------------------------------------------------------------- | | Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled | | Tags | `param` | | Aliases | `arg`, `argument` | |Recommended | true| | Options |`autoIncrementBase`, `checkConstructors`, `checkDestructured`, `checkDestructuredRoots`, `checkGetters`, `checkRestProperty`, `checkSetters`, `checkTypesPattern`, `contexts`, `enableFixer`, `enableRestElementFixer`, `enableRootFixer`, `exemptedBy`, `ignoreWhenAllParamsMissing`, `interfaceExemptsParamsCheck`, `unnamedRootBase`, `useDefaultObjectProperties`| | Settings | `ignoreReplacesDocs`, `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs`| ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux (foo) { } // Message: Missing JSDoc @param "foo" declaration. /** * */ function quux (foo) { } // "jsdoc/require-param": ["error"|"warn", {"contexts":["FunctionDeclaration"]}] // Message: Missing JSDoc @param "foo" declaration. /** * */ function quux ({foo}) { } // Message: Missing JSDoc @param "root0" declaration. /** * @param foo */ function quux (foo, bar, {baz}) { } // "jsdoc/require-param": ["error"|"warn", {"checkDestructured":false}] // Message: Missing JSDoc @param "bar" declaration. /** * @param foo */ function quux (foo, bar, {baz}) { } // "jsdoc/require-param": ["error"|"warn", {"checkDestructuredRoots":false}] // Message: Missing JSDoc @param "bar" declaration. /** * */ function quux ({foo}) { } // "jsdoc/require-param": ["error"|"warn", {"enableFixer":false}] // Message: Missing JSDoc @param "root0" declaration. /** * */ function quux ({foo: bar = 5} = {}) { } // Message: Missing JSDoc @param "root0" declaration. /** * @param */ function quux ({foo}) { } // Message: Missing JSDoc @param "root0" declaration. /** * @param */ function quux ({foo}) { } // "jsdoc/require-param": ["error"|"warn", {"autoIncrementBase":1}] // Message: Missing JSDoc @param "root1" declaration. /** * @param options */ function quux ({foo}) { } // Message: Missing JSDoc @param "options.foo" declaration. /** * @param */ function quux ({ foo, bar: { baz }}) { } // Message: Missing JSDoc @param "root0" declaration. /** * @param root0 * @param root0.foo * @param root0.bar.baz */ function quux ({ foo, bar: { baz }}) { } // Message: Missing JSDoc @param "root0.bar" declaration. /** * */ function quux ({foo}, {bar}) { } // "jsdoc/require-param": ["error"|"warn", {"unnamedRootBase":["arg"]}] // Message: Missing JSDoc @param "arg0" declaration. /** * */ function quux ({foo}, {bar}) { } // "jsdoc/require-param": ["error"|"warn", {"unnamedRootBase":["arg","config"]}] // Message: Missing JSDoc @param "arg" declaration. /** * */ function quux ({foo}, {bar}) { } // "jsdoc/require-param": ["error"|"warn", {"enableRootFixer":false,"unnamedRootBase":["arg","config"]}] // Message: Missing JSDoc @param "arg" declaration. /** * */ function quux (foo, bar) { } // Message: Missing JSDoc @param "foo" declaration. /** * @param foo */ function quux (foo, bar) { } // Message: Missing JSDoc @param "bar" declaration. /** * @param bar */ function quux (foo, bar, baz) { } // Message: Missing JSDoc @param "foo" declaration. /** * @param foo * @param bar */ function quux (foo, bar, baz) { } // Message: Missing JSDoc @param "baz" declaration. /** * @param baz */ function quux (foo, bar, baz) { } // Message: Missing JSDoc @param "foo" declaration. /** * @param */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} // Message: Missing JSDoc @arg "foo" declaration. /** * @override */ function quux (foo) { } // Settings: {"jsdoc":{"overrideReplacesDocs":false}} // Message: Missing JSDoc @param "foo" declaration. /** * @ignore */ function quux (foo) { } // Settings: {"jsdoc":{"ignoreReplacesDocs":false}} // Message: Missing JSDoc @param "foo" declaration. /** * @implements */ function quux (foo) { } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // Message: Missing JSDoc @param "foo" declaration. /** * @augments */ function quux (foo) { } // Message: Missing JSDoc @param "foo" declaration. /** * @extends */ function quux (foo) { } // Message: Missing JSDoc @param "foo" declaration. /** * @override */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"overrideReplacesDocs":false}} // Message: Missing JSDoc @param "foo" declaration. /** * @ignore */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"ignoreReplacesDocs":false}} // Message: Missing JSDoc @param "foo" declaration. /** * @implements */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"implementsReplacesDocs":false}} // Message: Missing JSDoc @param "foo" declaration. /** * @augments */ class A { /** * */ quux (foo) { } } // Message: Missing JSDoc @param "foo" declaration. /** * @extends */ class A { /** * */ quux (foo) { } } // Message: Missing JSDoc @param "foo" declaration. export class SomeClass { /** * @param property */ constructor(private property: string, private foo: number) {} } // Message: Missing JSDoc @param "foo" declaration. /** * @param */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":false}}} // Message: Unexpected tag `@param` /** * */ function quux ({bar, baz}, foo) { } // Message: Missing JSDoc @param "root0" declaration. /** * */ function quux (foo, {bar, baz}) { } // Message: Missing JSDoc @param "foo" declaration. /** * */ function quux ([bar, baz], foo) { } // Message: Missing JSDoc @param "root0" declaration. /** * */ function quux (foo) { } // "jsdoc/require-param": ["error"|"warn", {"exemptedBy":["notPresent"]}] // Message: Missing JSDoc @param "foo" declaration. /** * @inheritdoc */ function quux (foo) { } // "jsdoc/require-param": ["error"|"warn", {"exemptedBy":[]}] // Message: Missing JSDoc @param "foo" declaration. /** * @inheritdoc */ function quux (foo) { } // Settings: {"jsdoc":{"mode":"closure"}} // Message: Missing JSDoc @param "foo" declaration. /** * Assign the project to a list of employees. * @param {object[]} employees - The employees who are responsible for the project. * @param {string} employees[].name - The name of an employee. * @param {string} employees[].department - The employee's department. */ function assign (employees, name) { }; // Message: Missing JSDoc @param "name" declaration. interface ITest { /** * Test description. */ TestMethod(id: number): void; } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSMethodSignature"]}] // Message: Missing JSDoc @param "id" declaration. /** * A test class. */ abstract class TestClass { /** * A test method. */ abstract TestFunction(id); } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSEmptyBodyFunctionExpression"]}] // Message: Missing JSDoc @param "id" declaration. /** * A test class. */ declare class TestClass { /** * */ TestMethod(id); } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSEmptyBodyFunctionExpression"]}] // Message: Missing JSDoc @param "id" declaration. /** * A test function. */ declare let TestFunction: (id) => void; // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. /** * A test function. */ let TestFunction: (id) => void; // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. /** * A test function. */ function test( processor: (id: number) => string ) { return processor(10); } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. /** * A test function. */ let test = (processor: (id: number) => string) => { return processor(10); } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. class TestClass { /** * A class property. */ public Test: (id: number) => string; } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. class TestClass { /** * A class method. */ public TestMethod(): (id: number) => string { } } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. interface TestInterface { /** * An interface property. */ Test: (id: number) => string; } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. interface TestInterface { /** * An interface method. */ TestMethod(): (id: number) => string; } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. /** * A function with return type */ function test(): (id: number) => string; // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. /** * A function with return type */ let test = (): (id: number) => string => { return (id) => `${id}`; } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "id" declaration. /** * @param baz * @param options */ function quux (baz, {foo: bar}) { } // Message: Missing JSDoc @param "options.foo" declaration. class Client { /** * Set collection data. * @param {Object} data The collection data object. * @param {number} data.last_modified * @param {Object} options The options object. * @param {Object} [options.headers] The headers object option. * @param {Number} [options.retry=0] Number of retries to make * when faced with transient errors. * @param {Boolean} [options.safe] The safe option. * @param {Boolean} [options.patch] The patch option. * @param {Number} [options.last_modified] The last_modified option. * @return {Promise} */ async setData( data: { last_modified?: number }, options: { headers?: Record; safe?: boolean; retry?: number; patch?: boolean; last_modified?: number; permissions?: []; } = {} ) {} } // Message: Missing JSDoc @param "options.permissions" declaration. /** * */ function quux (foo) { } // "jsdoc/require-param": ["error"|"warn", {"enableFixer":false}] // Message: Missing JSDoc @param "foo" declaration. class Client { /** * Set collection data. * @return {Promise} */ async setData( data: { last_modified?: number } ) {} } // Message: Missing JSDoc @param "data" declaration. /** * @param cfg * @param cfg.num */ function quux ({num, ...extra}) { } // "jsdoc/require-param": ["error"|"warn", {"checkRestProperty":true}] // Message: Missing JSDoc @param "cfg.extra" declaration. /** * @param cfg * @param cfg.opts * @param cfg.opts.num */ function quux ({opts: {num, ...extra}}) { } // "jsdoc/require-param": ["error"|"warn", {"checkRestProperty":true}] // Message: Missing JSDoc @param "cfg.opts.extra" declaration. /** * @param {GenericArray} cfg * @param {number} cfg."0" */ function baar ([a, ...extra]) { // } // Message: Missing JSDoc @param "cfg."1"" declaration. /** * @param a */ function baar (a, ...extra) { // } // Message: Missing JSDoc @param "extra" declaration. /** * Converts an SVGRect into an object. * @param {SVGRect} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; // "jsdoc/require-param": ["error"|"warn", {"checkTypesPattern":"SVGRect"}] // Message: Missing JSDoc @param "bbox.x" declaration. /** * Converts an SVGRect into an object. * @param {object} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; // Message: Missing JSDoc @param "bbox.x" declaration. module.exports = class GraphQL { /** * @param fetchOptions * @param cacheKey */ fetch = ({ url, ...options }, cacheKey) => { } }; // "jsdoc/require-param": ["error"|"warn", {"checkRestProperty":true}] // Message: Missing JSDoc @param "fetchOptions.url" declaration. (function() { /** * A function. */ function f(param) { return !param; } })(); // Message: Missing JSDoc @param "param" declaration. /** * Description. * @param {Object} options * @param {Object} options.foo */ function quux ({ foo: { bar } }) {} // Message: Missing JSDoc @param "options.foo.bar" declaration. /** * Description. * @param {FooBar} options * @param {FooBar} options.foo */ function quux ({ foo: { bar } }) {} // "jsdoc/require-param": ["error"|"warn", {"checkTypesPattern":"FooBar"}] // Message: Missing JSDoc @param "options.foo.bar" declaration. /** * Description. * @param {Object} options * @param {FooBar} foo */ function quux ({ foo: { bar } }) {} // Message: Missing JSDoc @param "options.foo" declaration. /** * Description. * @param {Object} options * @param options.foo */ function quux ({ foo: { bar } }) {} // Message: Missing JSDoc @param "options.foo.bar" declaration. /** * Description. * @param {object} options Options. * @param {object} options.foo A description. * @param {object} options.foo.bar */ function foo({ foo: { bar: { baz } }}) {} // Message: Missing JSDoc @param "options.foo.bar.baz" declaration. /** * Returns a number. * @param {Object} props Props. * @param {Object} props.prop Prop. * @return {number} A number. */ export function testFn1 ({ prop = { a: 1, b: 2 } }) { } // "jsdoc/require-param": ["error"|"warn", {"useDefaultObjectProperties":true}] // Message: Missing JSDoc @param "props.prop.a" declaration. /** Foo. */ function foo(a, b, c) {} // Message: Missing JSDoc @param "a" declaration. /** * @param foo Some number. * @param bar Some number. */ export function myPublicFunction(foo: number, bar: number, baz: number) {} // "jsdoc/require-param": ["error"|"warn", {"contexts":[{"comment":"JsdocBlock:has(JsdocTag[tag=\"param\"])","context":"FunctionDeclaration"}]}] // Message: Missing JSDoc @param "baz" declaration. /** * [A description] */ class A { /** * openConfirmModal * @memberof CreateEditTestWizardComponent */ public openConfirmModal(btnState: string) { this.modalBtnState = btnState; this.openModal(); } } // "jsdoc/require-param": ["error"|"warn", {"contexts":["MethodDefinition"]}] // Message: Missing JSDoc @param "btnState" declaration. class A { /** * @param root0 * @param root0.foo */ quux({ foo }, { bar }) { console.log(foo, bar); } } // Message: Missing JSDoc @param "root1" declaration. /** * Some desc. * @param a */ function quux (a, b) {} // "jsdoc/require-param": ["error"|"warn", {"ignoreWhenAllParamsMissing":true}] // Message: Missing JSDoc @param "b" declaration. /** * Some test function type. */ export type Test = (foo: number) => string; // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] // Message: Missing JSDoc @param "foo" declaration. /** * */ const quux = function quux (foo) { }; // "jsdoc/require-param": ["error"|"warn", {"interfaceExemptsParamsCheck":true}] // Message: Missing JSDoc @param "foo" declaration. /** * */ function quux ({ abc, def }) { } // "jsdoc/require-param": ["error"|"warn", {"interfaceExemptsParamsCheck":true}] // Message: Missing JSDoc @param "root0" declaration. /** * @param foo * @param baz * @returns {number} */ function quux (foo, bar, baz) { return foo + bar + baz; } // Message: Missing JSDoc @param "bar" declaration. /** * @example * ```ts * app.use(checkResourceOwnership({ entryPoint: 'seller_product' })); * ``` * * @example * ```ts * app.use(checkResourceOwnership({ entryPoint: 'service_zone' })); * ``` * * @param options - configuration * @param options.entryPoint * @param options.filterField * @param options.paramIdField */ export const checkResourceOwnership = ({ entryPoint, filterField, paramIdField, resourceId = () => '' }) => {}; // Message: Missing JSDoc @param "options.resourceId" declaration. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param foo */ function quux (foo) { } /** * @param root0 * @param root0.foo */ function quux ({foo}) { } /** * @param root0 * @param root0.foo * @param root1 * @param root1.bar */ function quux ({foo}, {bar}) { } /** * @param arg0 * @param arg0.foo * @param arg1 * @param arg1.bar */ function quux ({foo}, {bar}) { } // "jsdoc/require-param": ["error"|"warn", {"unnamedRootBase":["arg"]}] /** * @param arg * @param arg.foo * @param config0 * @param config0.bar * @param config1 * @param config1.baz */ function quux ({foo}, {bar}, {baz}) { } // "jsdoc/require-param": ["error"|"warn", {"unnamedRootBase":["arg","config"]}] /** * @inheritdoc */ function quux (foo) { } /** * @inheritDoc */ function quux (foo) { } /** * @arg foo */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"param":"arg"}}} /** * @override * @param foo */ function quux (foo) { } /** * @override */ function quux (foo) { } /** * @override */ class A { /** * */ quux (foo) { } } /** * @override */ function quux (foo) { } // Settings: {"jsdoc":{"overrideReplacesDocs":true}} /** * @ignore */ function quux (foo) { } // Settings: {"jsdoc":{"ignoreReplacesDocs":true}} /** * @implements */ class A { /** * */ quux (foo) { } } /** * @implements */ function quux (foo) { } /** * @implements */ function quux (foo) { } // Settings: {"jsdoc":{"implementsReplacesDocs":true}} /** * @implements * @param foo */ function quux (foo) { } /** * @augments */ function quux (foo) { } // Settings: {"jsdoc":{"augmentsExtendsReplacesDocs":true}} /** * @augments * @param foo */ function quux (foo) { } /** * @extends */ function quux (foo) { } // Settings: {"jsdoc":{"augmentsExtendsReplacesDocs":true}} /** * @extends * @param foo */ function quux (foo) { } /** * @override */ class A { /** * @param foo */ quux (foo) { } } /** * @override */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"overrideReplacesDocs":true}} /** * @ignore */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"ignoreReplacesDocs":true}} /** * @implements */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"implementsReplacesDocs":true}} /** * @implements */ class A { /** * @param foo */ quux (foo) { } } /** * @augments */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"augmentsExtendsReplacesDocs":true}} /** * @augments */ class A { /** * @param foo */ quux (foo) { } } /** * @extends */ class A { /** * */ quux (foo) { } } // Settings: {"jsdoc":{"augmentsExtendsReplacesDocs":true}} /** * @extends */ class A { /** * @param foo */ quux (foo) { } } /** * @internal */ function quux (foo) { } // Settings: {"jsdoc":{"ignoreInternal":true}} /** * @private */ function quux (foo) { } // Settings: {"jsdoc":{"ignorePrivate":true}} /** * @access private */ function quux (foo) { } // Settings: {"jsdoc":{"ignorePrivate":true}} // issue 182: optional chaining /** @const {boolean} test */ const test = something?.find(_ => _) /** @type {RequestHandler} */ function foo(req, res, next) {} /** * @type {MyCallback} */ function quux () { } // "jsdoc/require-param": ["error"|"warn", {"exemptedBy":["type"]}] /** * @override */ var A = class { /** * */ quux (foo) { } } export class SomeClass { /** * @param property */ constructor(private property: string) {} } /** * Assign the project to an employee. * * @param {object} employee - The employee who is responsible for the project. * @param {string} employee.name - The name of the employee. * @param {string} employee.department - The employee's department. */ function assign({name, department}) { // ... } export abstract class StephanPlugin { /** * Called right after Stephan loads the plugin file. * * @example *```typescript * type Options = { * verbose?: boolean; * token?: string; * } * ``` * * Note that your Options type should only have optional properties... * * @param args Arguments compiled and provided by StephanClient. * @param args.options The options as provided by the user, or an empty object if not provided. * @param args.client The options as provided by the user, or an empty object if not provided. * @param defaultOptions The default options as provided by the plugin, or an empty object. */ public constructor({options, client}: { options: O; client: unknown; }, defaultOptions: D) { } } /** * */ function quux (foo) { } // "jsdoc/require-param": ["error"|"warn", {"contexts":["ArrowFunctionExpression"]}] /** * A function with return type * * @param id */ let test = (): (id: number) => string => { return (id) => `${id}`; } // "jsdoc/require-param": ["error"|"warn", {"contexts":["TSFunctionType"]}] /** @abstract */ class base { /** @param {boolean} arg0 */ constructor(arg0) {} } class foo extends base { /** @inheritDoc */ constructor(arg0) { super(arg0); this.arg0 = arg0; } } // Settings: {"jsdoc":{"mode":"closure"}} export abstract class StephanPlugin { /** * Called right after Stephan loads the plugin file. * * @example *```typescript * type Options = { * verbose?: boolean; * token?: string; * } * ``` * * Note that your Options type should only have optional properties... * * @param args Arguments compiled and provided by StephanClient. * @param args.options The options as provided by the user, or an empty object if not provided. * @param args.client The options as provided by the user, or an empty object if not provided. * @param args.client.name The name of the client. * @param defaultOptions The default options as provided by the plugin, or an empty object. */ public constructor({ options, client: { name } }: { options: O; client: { name: string }; }, defaultOptions: D) { } } /** * @param {string} cb */ function createGetter (cb) { return function (...args) { cb(); }; } /** * @param cfg * @param cfg.num */ function quux ({num, ...extra}) { } /** * @param {GenericArray} cfg * @param {number} cfg."0" */ function baar ([a, ...extra]) { // } // "jsdoc/require-param": ["error"|"warn", {"enableRestElementFixer":false}] /** * @param a */ function baar (a, ...extra) { // } // "jsdoc/require-param": ["error"|"warn", {"enableRestElementFixer":false}] /** * Converts an SVGRect into an object. * @param {SVGRect} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; /** * Converts an SVGRect into an object. * @param {object} bbox - a SVGRect */ const bboxToObj = function ({x, y, width, height}) { return {x, y, width, height}; }; // "jsdoc/require-param": ["error"|"warn", {"checkTypesPattern":"SVGRect"}] class CSS { /** * Set one or more CSS properties for the set of matched elements. * * @param {Object} propertyObject - An object of property-value pairs to set. */ setCssObject(propertyObject: {[key: string]: string | number}): void { } } /** * @param foo * @param bar * @param cfg */ function quux (foo, bar, {baz}) { } // "jsdoc/require-param": ["error"|"warn", {"checkDestructured":false}] /** * @param foo * @param bar */ function quux (foo, bar, {baz}) { } // "jsdoc/require-param": ["error"|"warn", {"checkDestructuredRoots":false}] /** * @param root * @param root.foo */ function quux ({"foo": bar}) { } /** * @param root * @param root."foo" */ function quux ({foo: bar}) { } /** * Description. * @param {string} b Description `/**`. */ module.exports = function a(b) { console.info(b); }; /** * Description. * @param {Object} options Options. * @param {FooBar} options.foo foo description. */ function quux ({ foo: { bar } }) {} /** * Description. * @param {FooBar} options * @param {Object} options.foo */ function quux ({ foo: { bar } }) {} // "jsdoc/require-param": ["error"|"warn", {"checkTypesPattern":"FooBar"}] /** * @param obj * @param obj.data * @param obj.data."0" * @param obj.data."1" * @param obj.data."2" * @param obj.defaulting * @param obj.defaulting."0" * @param obj.defaulting."1" */ function Item({ data: [foo, bar, ...baz], defaulting: [quux, xyz] = [] }) { } /** * Returns a number. * @param {Object} props Props. * @param {Object} props.prop Prop. * @return {number} A number. */ export function testFn1 ({ prop = { a: 1, b: 2 } }) { } // "jsdoc/require-param": ["error"|"warn", {"useDefaultObjectProperties":false}] /** * @param this The this object * @param bar number to return * @returns number returned back to caller */ function foo(this: T, bar: number): number { console.log(this.name); return bar; } /** * @param bar number to return * @returns number returned back to caller */ function foo(this: T, bar: number): number { console.log(this.name); return bar; } /** {@link someOtherval} */ function a (b) {} // "jsdoc/require-param": ["error"|"warn", {"contexts":[{"comment":"*:not(JsdocBlock:has(JsdocInlineTag[tag=link]))","context":"FunctionDeclaration"}]}] /** * Returns the sum of two numbers * @param options Object to destructure * @param options.a First value * @param options.b Second value * @returns Sum of a and b */ function sumDestructure(this: unknown, { a, b }: { a: number, b: number }) { return a + b; } /** * */ const inner = (c: number, d: string): void => { console.log(c); console.log(d); }; // Settings: {"jsdoc":{"contexts":["VariableDeclaration"]}} /** * Some desc. */ function quux (a, b) {} // "jsdoc/require-param": ["error"|"warn", {"ignoreWhenAllParamsMissing":true}] /** * Test function with param. * @param foo - Test param. */ function myFunction(foo: string): void; /** * Test function without param. */ function myFunction(): void; function myFunction(foo?: string) {} /** * */ const quux: FunctionInterface = function quux (foo) { }; // "jsdoc/require-param": ["error"|"warn", {"interfaceExemptsParamsCheck":true}] /** * */ function quux ({ abc, def }: FunctionInterface) { } // "jsdoc/require-param": ["error"|"warn", {"interfaceExemptsParamsCheck":true}] /** * */ export async function fetchMarketstackEOD( parameters: FetchEODParameters, ): Promise { // ... }; // "jsdoc/require-param": ["error"|"warn", {"interfaceExemptsParamsCheck":true}] ```` --- # require-property-description * [Context and settings](#user-content-require-property-description-context-and-settings) * [Failing examples](#user-content-require-property-description-failing-examples) * [Passing examples](#user-content-require-property-description-passing-examples) Requires that each `@property` tag has a `description` value. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`property`| |Aliases|`prop`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @typedef {SomeType} SomeTypedef * @property foo */ // Message: Missing JSDoc @property "foo" description. /** * @typedef {SomeType} SomeTypedef * @prop foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":"prop"}}} // Message: Missing JSDoc @prop "foo" description. /** * @typedef {SomeType} SomeTypedef * @property foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":false}}} // Message: Unexpected tag `@property` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @typedef {SomeType} SomeTypedef */ /** * @typedef {SomeType} SomeTypedef * @property foo Foo. */ /** * @namespace {SomeType} SomeName * @property foo Foo. */ /** * @class * @property foo Foo. */ /** * Typedef with multi-line property type. * * @typedef {object} MyType * @property {function( * number * )} numberEater Method which takes a number. */ ```` --- # require-property-name * [Context and settings](#user-content-require-property-name-context-and-settings) * [Failing examples](#user-content-require-property-name-failing-examples) * [Passing examples](#user-content-require-property-name-passing-examples) Requires that all `@property` tags have names. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`property`| |Aliases|`prop`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @typedef {SomeType} SomeTypedef * @property */ // Message: There must be an identifier after @property type. /** * @typedef {SomeType} SomeTypedef * @property {string} */ // Message: There must be an identifier after @property tag. /** * @typedef {SomeType} SomeTypedef * @property foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":false}}} // Message: Unexpected tag `@property` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @typedef {SomeType} SomeTypedef * @property foo */ /** * @typedef {SomeType} SomeTypedef * @property {string} foo */ /** * @namespace {SomeType} SomeName * @property {string} foo */ /** * @class * @property {string} foo */ ```` --- # require-property-type * [Context and settings](#user-content-require-property-type-context-and-settings) * [Failing examples](#user-content-require-property-type-failing-examples) * [Passing examples](#user-content-require-property-type-passing-examples) Requires that each `@property` tag has a type value (within curly brackets). ## Context and settings ||| |---|---| |Context|everywhere| |Tags|`property`| |Aliases|`prop`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @typedef {SomeType} SomeTypedef * @property foo */ // Message: Missing JSDoc @property "foo" type. /** * @typedef {SomeType} SomeTypedef * @prop foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":"prop"}}} // Message: Missing JSDoc @prop "foo" type. /** * @typedef {SomeType} SomeTypedef * @property foo */ // Settings: {"jsdoc":{"tagNamePreference":{"property":false}}} // Message: Unexpected tag `@property` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @typedef {SomeType} SomeTypedef */ /** * @typedef {SomeType} SomeTypedef * @property {number} foo */ /** * @namespace {SomeType} SomeName * @property {number} foo */ /** * @class * @property {number} foo */ ```` --- # require-property * [Fixer](#user-content-require-property-fixer) * [Context and settings](#user-content-require-property-context-and-settings) * [Failing examples](#user-content-require-property-failing-examples) * [Passing examples](#user-content-require-property-passing-examples) Requires that all `@typedef` and `@namespace` tags have `@property` tags when their type is a plain `object`, `Object`, or `PlainObject`. Note that any other type, including a subtype of object such as `object`, will not be reported. ## Fixer The fixer for `require-property` will add an empty `@property`. ## Context and settings ||| |---|---| |Context|Everywhere| |Tags|`typedef`, `namespace`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @typedef {object} SomeTypedef */ // Message: Missing JSDoc @property. class Test { /** * @typedef {object} SomeTypedef */ quux () {} } // Message: Missing JSDoc @property. /** * @typedef {PlainObject} SomeTypedef */ // Settings: {"jsdoc":{"tagNamePreference":{"property":"prop"}}} // Message: Missing JSDoc @prop. /** * @namespace {Object} SomeName */ // Message: Missing JSDoc @property. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ /** * @property */ /** * @typedef {Object} SomeTypedef * @property {SomeType} propName Prop description */ /** * @typedef {object} SomeTypedef * @prop {SomeType} propName Prop description */ // Settings: {"jsdoc":{"tagNamePreference":{"property":"prop"}}} /** * @typedef {object} SomeTypedef * @property * // arbitrary property content */ /** * @typedef {object} SomeTypedef */ /** * @typedef {string} SomeTypedef */ /** * @namespace {object} SomeName * @property {SomeType} propName Prop description */ /** * @namespace {object} SomeName * @property * // arbitrary property content */ /** * @typedef {object} SomeTypedef * @property someProp * @property anotherProp This with a description * @property {anotherType} yetAnotherProp This with a type and desc. */ function quux () { } ```` --- # require-rejects Requires a (non-standard) `@rejects` tag be added for detectable `Promise` rejections. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or objects with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@rejects`. Defaults to an array with `abstract`, `virtual`, and `type`. If you set this array, it will overwrite the default, so be sure to add back those tags if you wish their presence to cause exemption of the rule. ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|false| |Settings|| |Options|`contexts`, `exemptedBy`| ## Failing examples The following patterns are considered problems: ````ts /** * */ async function quux () { throw new Error('abc'); } // Message: Promise-rejecting function requires `@rejects` tag /** * */ const quux = async () => { throw new Error('abc'); }; // Message: Promise-rejecting function requires `@rejects` tag /** * */ const quux = async function () { throw new Error('abc'); }; // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { try { await sthAsync(); } catch (err) { if (cond) { throw err; } } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ function quux () { return new Promise((resolve, reject) => { reject(new Error('abc')); }); } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { if (cond) { throw new Error('abc'); } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { function inner () { if (cond) { throw new Error('abc'); } } inner(); } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { return Promise.reject(new Error('abc')); } // Message: Promise-rejecting function requires `@rejects` tag /** * */ function quux () { if (cond) { return Promise.reject(new Error('abc')); } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { for (let i = 0; i < 10; i++) { if (i > 5) { throw new Error('abc'); } } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { while (cond) { throw new Error('abc'); } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { switch (val) { case 1: throw new Error('abc'); case 2: break; } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { const arr = [1, 2, 3]; for (const item of arr) { if (item > 2) { throw new Error('abc'); } } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { const obj = {a: 1, b: 2}; for (const key in obj) { if (key === 'a') { throw new Error('abc'); } } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { do { throw new Error('abc'); } while (cond); } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { label: { throw new Error('abc'); } } // Message: Promise-rejecting function requires `@rejects` tag /** * */ async function quux () { try { doSomething(); } finally { throw new Error('cleanup failed'); } } // Message: Promise-rejecting function requires `@rejects` tag ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @rejects {Error} */ async function quux () { throw new Error('abc'); } /** * @abstract */ async function quux () { throw new Error('abc'); } /** * */ function quux () { return 42; } /** * */ async function quux () { return await sthAsync(); } /** * */ async function quux () { if (cond) { return; } } /** * */ async function quux () { const obj = new SomeClass(); } /** * */ function quux () { const p = new Promise(someVariable); } /** * */ function quux () { return new Promise(someVariable); } /** * */ async function quux () { someFunction(); } /** * */ async function quux () { try { doSomething(); } catch (err) { console.error(err); } } /** * */ async function quux () { try { throw new Error('wholly caught'); } catch (err) { console.error(err); } } /** * */ async function quux () { if (cond) { doSomething(); } else { doOtherThing(); } } /** * @callback MyCallback */ // "jsdoc/require-rejects": ["error"|"warn", {"contexts":["any"]}] /** * */ async function quux () { throw new Error('abc'); } // Settings: {"jsdoc":{"tagNamePreference":{"rejects":false}}} /** @param bar Something. */ export function foo(bar: string): void { throw new Error(`some error: ${bar}`); } ```` --- # require-returns-check * [Options](#user-content-require-returns-check-options) * [`exemptAsync`](#user-content-require-returns-check-options-exemptasync) * [`exemptGenerators`](#user-content-require-returns-check-options-exemptgenerators) * [`noNativeTypes`](#user-content-require-returns-check-options-nonativetypes) * [`reportMissingReturnForUndefinedTypes`](#user-content-require-returns-check-options-reportmissingreturnforundefinedtypes) * [Context and settings](#user-content-require-returns-check-context-and-settings) * [Failing examples](#user-content-require-returns-check-failing-examples) * [Passing examples](#user-content-require-returns-check-passing-examples) Requires a return statement (or non-`undefined` Promise resolve value) be present in a function body if a `@returns` tag (without a `void` or `undefined` type) is specified in the function's JSDoc comment block. Will also report `@returns {void}` and `@returns {undefined}` if `exemptAsync` is set to `false` and a non-`undefined` value is returned or a resolved value is found. Also reports if `@returns {never}` is discovered with a return value. Will report if native types are specified for `@returns` on an async function. Will also report if multiple `@returns` tags are present. ## Options A single options object has the following properties. ### exemptAsync By default, functions which return a `Promise` that are not detected as resolving with a non-`undefined` value and `async` functions (even ones that do not explicitly return a value, as these are returning a `Promise` implicitly) will be exempted from reporting by this rule. If you wish to insist that only `Promise`'s which resolve to non-`undefined` values or `async` functions with explicit `return`'s will be exempted from reporting (i.e., that `async` functions can be reported if they lack an explicit (non-`undefined`) `return` when a `@returns` is present), you can set `exemptAsync` to `false` on the options object. ### exemptGenerators Because a generator might be labeled as having a `IterableIterator` `@returns` value (along with an iterator type corresponding to the type of any `yield` statements), projects might wish to leverage `@returns` in generators even without a `return` statement. This option is therefore `true` by default in `typescript` mode (in "jsdoc" mode, one might be more likely to take advantage of `@yields`). Set it to `false` if you wish for a missing `return` to be flagged regardless. ### noNativeTypes Whether to check that async functions do not indicate they return non-native types. Defaults to `true`. ### reportMissingReturnForUndefinedTypes If `true` and no return or resolve value is found, this setting will even insist that reporting occur with `void` or `undefined` (including as an indicated `Promise` type). Unlike `require-returns`, with this option in the rule, one can *discourage* the labeling of `undefined` types. Defaults to `false`. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`| |Tags|`returns`| |Aliases|`return`| |Options|`exemptAsync`, `exemptGenerators`, `noNativeTypes`, `reportMissingReturnForUndefinedTypes`| |Recommended|true| ## Failing examples The following patterns are considered problems: ````ts /** * @returns */ function quux (foo) { } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @return */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":"return"}}} // Message: JSDoc @return declaration present but return expression not available in function. /** * @returns */ const quux = () => {} // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {undefined} Foo. * @returns {String} Foo. */ function quux () { return foo; } // Message: Found more than one @returns declaration. const language = { /** * @param {string} name * @returns {string} */ get name() { this._name = name; } } // Message: JSDoc @returns declaration present but return expression not available in function. class Foo { /** * @returns {string} */ bar () { } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":false}}} // Message: Unexpected tag `@returns` /** * @returns {string} */ function f () { function g() { return 'foo' } () => { return 5 } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {Promise} */ async function quux() {} // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {IterableIterator} */ function * quux() {} // Settings: {"jsdoc":{"mode":"jsdoc"}} // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {IterableIterator} */ function * quux() {} // Settings: {"jsdoc":{"mode":"typescript"}} // "jsdoc/require-returns-check": ["error"|"warn", {"exemptGenerators":false}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {Promise} */ function quux() { return new Promise((resolve, reject) => {}) } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {Promise} */ function quux() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }); }) } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * Description. * @returns {SomeType} */ async function foo() { return new Promise(resolve => resolve()); } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * Description. * @returns {void} */ async function foo() { return new Promise(resolve => resolve()); } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false,"reportMissingReturnForUndefinedTypes":true}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns { void } Foo. */ function quux () {} // "jsdoc/require-returns-check": ["error"|"warn", {"reportMissingReturnForUndefinedTypes":true}] // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {never} Foo. */ function quux () { return undefined; } // Message: JSDoc @returns declaration set with "never" but return expression is present in function. /** * @returns {never} */ function quux (foo) { return foo; } // Message: JSDoc @returns declaration set with "never" but return expression is present in function. /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns The file contents as buffer. */ export function readFixture(path: string): void; // Message: JSDoc @returns declaration present but return expression not available in function. /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns The file contents as buffer. */ export function readFixture(path: string); // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {SomeType} */ function quux (path) { if (true) { return; } return 15; }; // Message: JSDoc @returns declaration present but return expression not available in function. /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns The file contents as buffer. */ export function readFixture(path: string): void { return; }; // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {true} */ function quux () { if (true) { return true; } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {true} */ function quux () { if (true) { } else { return; } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {true} */ function quux (someVar) { switch (someVar) { case 1: return true; case 2: return; } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {boolean} */ const quux = (someVar) => { if (someVar) { return true; } }; // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {true} */ function quux () { try { return true; } catch (error) { } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {true} */ function quux () { try { return true; } catch (error) { return true; } finally { return; } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {true} */ function quux () { if (true) { throw new Error('abc'); } throw new Error('def'); } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {SomeType} Baz. */ function foo() { switch (true) { default: switch (false) { default: return; } return "baz"; } }; // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {number} */ function foo() { let n = 1; while (n > 0.5) { n = Math.random(); if (n < 0.2) { return n; } } } // Message: JSDoc @returns declaration present but return expression not available in function. /** * @returns {number} */ async function quux (foo) { } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] // Message: Function is async or otherwise returns a Promise but the return type is a native type. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @returns Foo. */ function quux () { return foo; } /** * @returns {string} Foo. */ function quux () { return foo; } /** * */ function quux () { } /** * @returns {SomeType} Foo. */ const quux = () => foo; /** * @returns {undefined} Foo. */ function quux () {} /** * @returns { void } Foo. */ function quux () {} /** * @returns {Promise} */ async function quux() {} /** * @returns {Promise} */ const quux = async function () {} /** * @returns {Promise} */ const quux = async () => {} /** * @returns Foo. * @abstract */ function quux () { throw new Error('must be implemented by subclass!'); } /** * @returns Foo. * @virtual */ function quux () { throw new Error('must be implemented by subclass!'); } /** * @returns Foo. * @constructor */ function quux () { } /** * @interface */ class Foo { /** * @returns {string} */ bar () { } } /** * @record */ class Foo { /** * @returns {string} */ bar () { } } // Settings: {"jsdoc":{"mode":"closure"}} /** * @returns {undefined} Foo. */ function quux () { } /** * @returns {void} Foo. */ function quux () { } /** * @returns {void} Foo. */ function quux () { return undefined; } /** * @returns {never} Foo. */ function quux () { } /** * @returns {void} Foo. */ function quux () { return; } /** * */ function quux () { return undefined; } /** * */ function quux () { return; } /** * @returns {true} */ function quux () { try { return true; } catch (err) { } return true; } /** * @returns {true} */ function quux () { try { } finally { return true; } return true; } /** * @returns {true} */ function quux () { try { something(); } catch (err) { return true; } return true; } /** * @returns {true} */ function quux () { switch (true) { case 'abc': return true; } return true; } /** * @returns {true} */ function quux () { for (const i of abc) { return true; } return true; } /** * @returns {true} */ function quux () { for (const a in b) { return true; } } /** * @returns {true} */ function quux () { for (const a of b) { return true; } } /** * @returns {true} */ function quux () { loop: for (const a of b) { return true; } } /** * @returns {true} */ function quux () { for (let i=0; i} */ async function quux() { return 5; } /** * @returns {Promise} */ async function quux() { return 5; } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] /** * @returns {Promise} */ function quux() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(true); }); }) } // "jsdoc/require-returns-check": ["error"|"warn", {"exemptAsync":false}] /** * Description. * @returns {void} */ async function foo() { return new Promise(resolve => resolve()); } // "jsdoc/require-returns-check": ["error"|"warn", {"reportMissingReturnForUndefinedTypes":true}] /** * @returns { void } Foo. */ function quux () { return undefined; } // "jsdoc/require-returns-check": ["error"|"warn", {"reportMissingReturnForUndefinedTypes":true}] /** * @returns { string } Foo. */ function quux () { return 'abc'; } // "jsdoc/require-returns-check": ["error"|"warn", {"reportMissingReturnForUndefinedTypes":true}] /** * @returns {IterableIterator} */ function * quux() {} // Settings: {"jsdoc":{"mode":"typescript"}} /** * @returns {IterableIterator} */ function * quux() {} // Settings: {"jsdoc":{"mode":"jsdoc"}} // "jsdoc/require-returns-check": ["error"|"warn", {"exemptGenerators":true}] /** * @param {unknown} val * @returns { asserts val is number } */ function assertNumber(val) { assert(typeof val === 'number'); } /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns The file contents as buffer. */ export function readFixture(path: string): Promise; /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns {SomeType} The file contents as buffer. */ export function readFixture(path: string): Promise; /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns The file contents as buffer. */ export function readFixture(path: string): Promise { return new Promise(() => {}); } /** * Reads a test fixture. * * @param path The path to resolve relative to the fixture base. It will be normalized for the * operating system. * * @returns {void} The file contents as buffer. */ export function readFixture(path: string); /** * @returns {SomeType} */ function quux (path) { if (true) { return 5; } return 15; }; /** * @returns {SomeType} Foo. */ const quux = () => new Promise((resolve) => { resolve(3); }); /** * @returns {SomeType} Foo. */ const quux = function () { return new Promise((resolve) => { resolve(3); }); }; /** * @returns {true} */ function quux () { if (true) { return true; } throw new Error('Fail'); } /** * @returns Baz. */ function foo() { switch (true) { default: switch (false) { default: break; } return "baz"; } }; /** * Return a V1 style query identifier. * * @param {string} id - The query identifier. * @returns {string} V1 style query identifier. */ function v1QueryId(id) { switch (id) { case 'addq': case 'aliq': case 'locq': return id.substring(3); case 'lost': return id.substring(4); default: return id; } } /** * Parses the required header fields for the given SIP message. * * @param {string} logPrefix - The log prefix. * @param {string} sipMessage - The SIP message. * @param {string[]} headers - The header fields to be parsed. * @returns {object} Object with parsed header fields. */ function parseSipHeaders(logPrefix, sipMessage, headers) { try { return esappSip.parseHeaders(sipMessage, headers); } catch (err) { logger.error(logPrefix, 'Failed to parse'); return {}; } } /** * @returns {true} */ function quux () { try { } catch (error) { } finally { return true; } } /** Returns true. * * @returns {boolean} true */ function getTrue() { try { return true; } finally { console.log('returning...'); } } /** * Maybe return a boolean. * @returns {boolean|void} true, or undefined. */ function maybeTrue() { if (Math.random() > 0.5) { return true; } } /** * @param {AST} astNode * @returns {AST} */ const getTSFunctionComment = function (astNode) { switch (greatGrandparent.type) { case 'VariableDeclarator': if (greatGreatGrandparent.type === 'VariableDeclaration') { return greatGreatGrandparent; } default: return astNode; } }; const f = /** * Description. * * @returns Result. */ () => { return function () {}; }; /** * Description. * * @returns Result. */ export function f(): string { return ""; interface I {} } /** * @param {boolean} bar A fun variable. * @returns {*} Anything at all! */ function foo( bar ) { if ( bar ) { return functionWithUnknownReturnType(); } } /** * @returns Baz. */ function foo() { switch (true) { default: switch (false) { default: return; } return "baz"; } }; /** * @returns */ const quux = (someVar) => { if (someVar) { return true; } }; /** * @returns {number} */ function foo() { while (true) { const n = Math.random(); if (n < 0.5) { return n; } } } /** * @returns {number} */ function foo() { for (;;) { const n = Math.random(); if (n < 0.5) { return n; } } } ```` --- # require-returns-description * [Options](#user-content-require-returns-description-options) * [`contexts`](#user-content-require-returns-description-options-contexts) * [Context and settings](#user-content-require-returns-description-context-and-settings) * [Failing examples](#user-content-require-returns-description-failing-examples) * [Passing examples](#user-content-require-returns-description-passing-examples) Requires that the `@returns` tag has a `description` value. The error will not be reported if the return value is `void` or `undefined` or if it is `Promise` or `Promise`. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`returns`| |Aliases|`return`| |Recommended|true| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * @returns */ function quux (foo) { } // Message: Missing JSDoc @returns description. /** * @returns {string} */ function quux (foo) { } // Message: Missing JSDoc @returns description. /** * @returns {string} */ function quux (foo) { } // "jsdoc/require-returns-description": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @returns description. /** * @function * @returns {string} */ // "jsdoc/require-returns-description": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @returns description. /** * @callback * @returns {string} */ // "jsdoc/require-returns-description": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @returns description. /** * @return */ function quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":"return"}}} // Message: Missing JSDoc @return description. /** * @returns */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":false}}} // Message: Unexpected tag `@returns` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * */ function quux () { } /** * @returns Foo. */ function quux () { } /** * @returns Foo. */ function quux () { } // "jsdoc/require-returns-description": ["error"|"warn", {"contexts":["any"]}] /** * @returns {undefined} */ function quux () { } /** * @returns {void} */ function quux () { } /** * @returns {Promise} */ function quux () { } /** * @returns {Promise} */ function quux () { } /** * @function * @returns */ /** * @callback * @returns */ ```` --- # require-returns-type * [Options](#user-content-require-returns-type-options) * [`contexts`](#user-content-require-returns-type-options-contexts) * [Context and settings](#user-content-require-returns-type-context-and-settings) * [Failing examples](#user-content-require-returns-type-failing-examples) * [Passing examples](#user-content-require-returns-type-passing-examples) Requires that `@returns` tag has a `type` value (in curly brackets). ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or an object with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). See the ["AST and Selectors"](#user-content-eslint-plugin-jsdoc-advanced-ast-and-selectors) section of our Advanced docs for more on the expected format. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled| |Tags|`returns`| |Aliases|`return`| |Recommended|true| |Options|`contexts`| ## Failing examples The following patterns are considered problems: ````ts /** * @returns */ function quux () { } // Message: Missing JSDoc @returns type. /** * @returns Foo. */ function quux () { } // Message: Missing JSDoc @returns type. /** * @returns Foo. */ function quux () { } // "jsdoc/require-returns-type": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @returns type. /** * @function * @returns Foo. */ // "jsdoc/require-returns-type": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @returns type. /** * @callback * @returns Foo. */ // "jsdoc/require-returns-type": ["error"|"warn", {"contexts":["any"]}] // Message: Missing JSDoc @returns type. /** * @return Foo. */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":"return"}}} // Message: Missing JSDoc @return type. /** * @returns */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":false}}} // Message: Unexpected tag `@returns` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @returns {number} */ function quux () { } /** * @returns {number} */ function quux () { } // "jsdoc/require-returns-type": ["error"|"warn", {"contexts":["any"]}] /** * @function * @returns Foo. */ /** * @callback * @returns Foo. */ ```` --- # require-returns * [Fixer](#user-content-require-returns-fixer) * [Options](#user-content-require-returns-options) * [`checkConstructors`](#user-content-require-returns-options-checkconstructors) * [`checkGetters`](#user-content-require-returns-options-checkgetters) * [`contexts`](#user-content-require-returns-options-contexts) * [`enableFixer`](#user-content-require-returns-options-enablefixer) * [`exemptedBy`](#user-content-require-returns-options-exemptedby) * [`forceRequireReturn`](#user-content-require-returns-options-forcerequirereturn) * [`forceReturnsWithAsync`](#user-content-require-returns-options-forcereturnswithasync) * [`publicOnly`](#user-content-require-returns-options-publiconly) * [Context and settings](#user-content-require-returns-context-and-settings) * [Failing examples](#user-content-require-returns-failing-examples) * [Passing examples](#user-content-require-returns-passing-examples) Requires that return statements are documented. Will also report if multiple `@returns` tags are present. ## Fixer Adds a blank `@returns`. ## Options A single options object has the following properties. ### checkConstructors A value indicating whether `constructor`s should be checked for `@returns` tags. Defaults to `false`. ### checkGetters Boolean to determine whether getter methods should be checked for `@returns` tags. Defaults to `true`. ### contexts Set this to an array of strings representing the AST context (or objects with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). This rule will only apply on non-default contexts when there is such a tag present and the `forceRequireReturn` option is set or if the `forceReturnsWithAsync` option is set with a present `@async` tag (since we are not checking against the actual `return` values in these cases). ### enableFixer Whether to enable the fixer to add a blank `@returns`. Defaults to `false`. ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@returns`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ### forceRequireReturn Set to `true` to always insist on `@returns` documentation regardless of implicit or explicit `return`'s in the function. May be desired to flag that a project is aware of an `undefined`/`void` return. Defaults to `false`. ### forceReturnsWithAsync By default `async` functions that do not explicitly return a value pass this rule as an `async` function will always return a `Promise`, even if the `Promise` resolves to void. You can force all `async` functions (including ones with an explicit `Promise` but no detected non-`undefined` `resolve` value) to require `@return` documentation by setting `forceReturnsWithAsync` to `true` on the options object. This may be useful for flagging that there has been consideration of return type. Defaults to `false`. ### publicOnly This option will insist that missing `@returns` are only reported for function bodies / class declarations that are exported from the module. May be a boolean or object. If set to `true`, the defaults below will be used. If unset, `@returns` reporting will not be limited to exports. This object supports the following optional boolean keys (`false` unless otherwise noted): - `ancestorsOnly` - Optimization to only check node ancestors to check if node is exported - `esm` - ESM exports are checked for `@returns` JSDoc comments (Defaults to `true`) - `cjs` - CommonJS exports are checked for `@returns` JSDoc comments (Defaults to `true`) - `window` - Window global exports are checked for `@returns` JSDoc comments ## Context and settings | | | | -------- | ------- | | Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled | | Tags | `returns` | | Aliases | `return` | |Recommended|true| | Options |`checkConstructors`, `checkGetters`, `contexts`, `enableFixer`, `exemptedBy`, `forceRequireReturn`, `forceReturnsWithAsync`, `publicOnly`| | Settings | `ignoreReplacesDocs`, `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` | ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux (foo) { return foo; } // Message: Missing JSDoc @returns declaration. /** * */ function quux (foo) { return foo; } // "jsdoc/require-returns": ["error"|"warn", {"enableFixer":true}] // Message: Missing JSDoc @returns declaration. /** * */ const foo = () => ({ bar: 'baz' }) // Message: Missing JSDoc @returns declaration. /** * */ const foo = bar=>({ bar }) // Message: Missing JSDoc @returns declaration. /** * */ const foo = bar => bar.baz() // Message: Missing JSDoc @returns declaration. /** * */ function quux (foo) { return foo; } // Settings: {"jsdoc":{"tagNamePreference":{"returns":"return"}}} // Message: Missing JSDoc @return declaration. /** * */ async function quux() { } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * */ const quux = async function () {} // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * */ const quux = async () => {} // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * */ async function quux () {} // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * */ function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * */ function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * @function */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * @callback */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. const language = { /** * @param {string} name */ get name() { return this._name; } } // Message: Missing JSDoc @returns declaration. /** * */ async function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. /** * @function * @async */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. /** * @callback * @async */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. /** * @returns {undefined} * @returns {void} */ function quux (foo) { return foo; } // Message: Found more than one @returns declaration. /** * @returns */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"returns":false}}} // Message: Unexpected tag `@returns` /** * @param foo */ function quux (foo) { return 'bar'; } // "jsdoc/require-returns": ["error"|"warn", {"exemptedBy":["notPresent"]}] // Message: Missing JSDoc @returns declaration. /** * @param {array} a */ async function foo(a) { return; } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. /** * @param {array} a */ async function foo(a) { return Promise.all(a); } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. class foo { /** gets bar */ get bar() { return 0; } } // "jsdoc/require-returns": ["error"|"warn", {"checkGetters":true}] // Message: Missing JSDoc @returns declaration. class TestClass { /** * */ constructor() { return new Map(); } } // "jsdoc/require-returns": ["error"|"warn", {"checkConstructors":true}] // Message: Missing JSDoc @returns declaration. class TestClass { /** * */ get Test() { return 0; } } // "jsdoc/require-returns": ["error"|"warn", {"checkGetters":true}] // Message: Missing JSDoc @returns declaration. class quux { /** * */ quux () { } } // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * */ function quux (foo) { return new Promise(function (resolve, reject) { resolve(foo); }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux (foo) { return new Promise(function (resolve, reject) { setTimeout(() => { resolve(true); }); }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux (foo) { return new Promise(function (resolve, reject) { foo(resolve); }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { while(true) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { do { resolve(true); } while(true) }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { if (true) { resolve(true); } return; }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { if (true) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { var a = {}; return new Promise((resolve, reject) => { with (a) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { var a = {}; return new Promise((resolve, reject) => { try { resolve(true); } catch (err) {} }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { var a = {}; return new Promise((resolve, reject) => { try { } catch (err) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { var a = {}; return new Promise((resolve, reject) => { try { } catch (err) { } finally { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { var a = {}; return new Promise((resolve, reject) => { switch (a) { case 'abc': resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { if (true) { resolve(); } else { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { for (let i = 0; i < 5 ; i++) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { for (const i of obj) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { for (const i in obj) { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { if (true) { return; } else { resolve(true); } }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise((resolve, reject) => { function a () { resolve(true); } a(); }); } // Message: Missing JSDoc @returns declaration. /** * */ function quux () { return new Promise(); } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. /** * */ async function quux () { return new Promise(); } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. /** * */ async function quux () { return new Promise((resolve, reject) => {}); } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] // Message: Missing JSDoc @returns declaration. export class A { /** * Description. */ public f(): string { return ""; } } export interface B { /** * Description. */ f(): string; /** * Description. */ g: () => string; /** * Description. */ h(): void; /** * Description. */ i: () => void; } /** * Description. */ export function f(): string { return ""; } // "jsdoc/require-returns": ["error"|"warn", {"contexts":[":not(BlockStatement) > FunctionDeclaration","MethodDefinition","TSMethodSignature","TSPropertySignature > TSTypeAnnotation > TSFunctionType"]}] // Message: Missing JSDoc @returns declaration. /** * @param ms time in millis */ export const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms)); // Message: Missing JSDoc @returns declaration. /** * @param ms time in millis */ export const sleep = (ms: number) => { return new Promise((res) => setTimeout(res, ms)); }; // Message: Missing JSDoc @returns declaration. /** * Reads a test fixture. */ export function readFixture(path: string): Promise; // Message: Missing JSDoc @returns declaration. /** * Reads a test fixture. */ export function readFixture(path: string): void; // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * Reads a test fixture. */ export function readFixture(path: string); // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] // Message: Missing JSDoc @returns declaration. /** * @param {array} a */ async function foo(a) { return Promise.all(a); } // Message: Missing JSDoc @returns declaration. /** * Description. */ export default async function demo() { return true; } // Message: Missing JSDoc @returns declaration. /** * */ function quux () {} class Test { /** * */ abstract Test(): string; } // "jsdoc/require-returns": ["error"|"warn", {"contexts":["FunctionDeclaration",{"context":"TSEmptyBodyFunctionExpression","forceRequireReturn":true}]}] // Message: Missing JSDoc @returns declaration. /** * */ module.exports = function quux (foo) { return foo; } // "jsdoc/require-returns": ["error"|"warn", {"publicOnly":true}] // Message: Missing JSDoc @returns declaration. /** * */ const a = function quux (foo) { return foo; }; export default a; // "jsdoc/require-returns": ["error"|"warn", {"publicOnly":true}] // Message: Missing JSDoc @returns declaration. /** * */ export default function quux (foo) { return foo; }; // "jsdoc/require-returns": ["error"|"warn", {"publicOnly":{"ancestorsOnly":true,"esm":true}}] // Message: Missing JSDoc @returns declaration. /** * */ exports.quux = function quux (foo) { return foo; }; // "jsdoc/require-returns": ["error"|"warn", {"publicOnly":{"cjs":true}}] // Message: Missing JSDoc @returns declaration. /** * */ window.quux = function quux (foo) { return foo; }; // "jsdoc/require-returns": ["error"|"warn", {"publicOnly":{"window":true}}] // Message: Missing JSDoc @returns declaration. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @returns Foo. */ function quux () { return foo; } /** * @returns Foo. */ function quux () { return foo; } // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"]}] /** * */ function quux () { } /** * */ function quux (bar) { bar.filter(baz => { return baz.corge(); }) } /** * @returns Array */ function quux (bar) { return bar.filter(baz => { return baz.corge(); }) } /** * @returns Array */ const quux = (bar) => bar.filter(({ corge }) => corge()) /** * @inheritdoc */ function quux (foo) { } /** * @override */ function quux (foo) { } /** * @constructor */ function quux (foo) { return true; } /** * @implements */ function quux (foo) { return true; } /** * @override */ function quux (foo) { return foo; } /** * @class */ function quux (foo) { return true; } /** * @constructor */ function quux (foo) { } /** * @returns {object} */ function quux () { return {a: foo}; } /** * @returns {object} */ const quux = () => ({a: foo}); /** * @returns {object} */ const quux = () => { return {a: foo} }; /** * @returns {void} */ function quux () { } /** * @returns {void} */ const quux = () => { } /** * @returns {undefined} */ function quux () { } /** * @returns {undefined} */ const quux = () => { } /** * */ const quux = () => { } class Foo { /** * */ constructor () { } } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] const language = { /** * @param {string} name */ set name(name) { this._name = name; } } /** * @returns {void} */ function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] /** * @returns {void} */ function quux () { return undefined; } /** * @returns {void} */ function quux () { return undefined; } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] /** * @returns {void} */ function quux () { return; } /** * @returns {void} */ function quux () { return; } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] /** @type {RequestHandler} */ function quux (req, res , next) { return; } /** * @returns {Promise} */ async function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] /** * @returns {Promise} */ async function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] /** * */ async function quux () {} /** * */ const quux = async function () {} /** * */ const quux = async () => {} /** foo class */ class foo { /** foo constructor */ constructor () { // => this.bar = true; } } export default foo; /** * */ function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] /** * @type {MyCallback} */ function quux () { } // "jsdoc/require-returns": ["error"|"warn", {"exemptedBy":["type"]}] /** * @param {array} a */ async function foo(a) { return; } /** * */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"]}] /** * @async */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"]}] /** * @function */ // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] /** * @callback */ // "jsdoc/require-returns": ["error"|"warn", {"forceRequireReturn":true}] /** * @function * @async */ // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] /** * @callback * @async */ // "jsdoc/require-returns": ["error"|"warn", {"forceReturnsWithAsync":true}] /** * @function */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceReturnsWithAsync":true}] /** * @callback */ // "jsdoc/require-returns": ["error"|"warn", {"contexts":["any"],"forceReturnsWithAsync":true}] class foo { get bar() { return 0; } } // "jsdoc/require-returns": ["error"|"warn", {"checkGetters":false}] class foo { /** @returns zero */ get bar() { return 0; } } // "jsdoc/require-returns": ["error"|"warn", {"checkGetters":true}] class foo { /** @returns zero */ get bar() { return 0; } } // "jsdoc/require-returns": ["error"|"warn", {"checkGetters":false}] class TestClass { /** * */ constructor() { } } class TestClass { /** * @returns A map. */ constructor() { return new Map(); } } class TestClass { /** * */ constructor() { } } // "jsdoc/require-returns": ["error"|"warn", {"checkConstructors":false}] class TestClass { /** * */ get Test() { } } class TestClass { /** * @returns A number. */ get Test() { return 0; } } class TestClass { /** * */ get Test() { return 0; } } // "jsdoc/require-returns": ["error"|"warn", {"checkGetters":false}] /** * */ function quux (foo) { return new Promise(function (resolve, reject) { resolve(); }); } /** * */ function quux (foo) { return new Promise(function (resolve, reject) { setTimeout(() => { resolve(); }); }); } /** * */ function quux (foo) { return new Promise(function (resolve, reject) { foo(); }); } /** * */ function quux (foo) { return new Promise(function (resolve, reject) { abc((resolve) => { resolve(true); }); }); } /** * */ function quux (foo) { return new Promise(function (resolve, reject) { abc(function (resolve) { resolve(true); }); }); } /** * */ function quux () { return new Promise((resolve, reject) => { if (true) { resolve(); } }); return; } /** * */ function quux () { return new Promise(); } /** * Description. */ async function foo() { return new Promise(resolve => resolve()); } /** * @param ms time in millis */ export const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms)); /** * @param ms time in millis */ export const sleep = (ms: number) => { return new Promise((res) => setTimeout(res, ms)); }; /** * Reads a test fixture. * * @returns The file contents as buffer. */ export function readFixture(path: string): Promise; /** * Reads a test fixture. * * @returns {void}. */ export function readFixture(path: string): void; /** * Reads a test fixture. */ export function readFixture(path: string): void; /** * Reads a test fixture. */ export function readFixture(path: string); /** * */ function quux () {} class Test { /** * @returns {string} The test value */ abstract Test(): string; } // "jsdoc/require-returns": ["error"|"warn", {"contexts":["FunctionDeclaration",{"context":"TSEmptyBodyFunctionExpression","forceRequireReturn":true}]}] /** * */ function quux (foo) { return foo; } // "jsdoc/require-returns": ["error"|"warn", {"publicOnly":true}] ```` --- # require-tags Requires tags be present, optionally for specific contexts. ## Options A single options object has the following properties. ### tags May be an array of either strings or objects with a string `tag` property and `context` string property. ||| |---|---| |Context|everywhere| |Tags|(Any)| |Recommended|false| |Settings|| |Options|`tags`| ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux () {} // "jsdoc/require-tags": ["error"|"warn", {"tags":["see"]}] // Message: Missing required tag "see" /** * */ function quux () {} // "jsdoc/require-tags": ["error"|"warn", {"tags":[{"context":"FunctionDeclaration","tag":"see"}]}] // Message: Missing required tag "see" /** * @type {SomeType} */ function quux () {} // "jsdoc/require-tags": ["error"|"warn", {"tags":[{"context":"FunctionDeclaration","tag":"see"}]}] // Message: Missing required tag "see" /** * @type {SomeType} */ function quux () {} // Message: Rule `require-tags` is missing a `tags` option. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @see */ function quux () {} // "jsdoc/require-tags": ["error"|"warn", {"tags":["see"]}] /** * */ class Quux {} // "jsdoc/require-tags": ["error"|"warn", {"tags":[{"context":"FunctionDeclaration","tag":"see"}]}] ```` --- # require-template-description ## Options ||| |---|---| |Context|everywhere| |Tags|`template`| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @template {SomeType} */ // Message: @template should have a description ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @template {SomeType} Has a description */ /** * @template Has a description */ ```` --- # require-template Checks to see that `@template` tags are present for any detected type parameters. Currently checks `ClassDeclaration`, `FunctionDeclaration`, `TSDeclareFunction`, `TSInterfaceDeclaration` or `TSTypeAliasDeclaration` such as: ```ts export type Pairs = [D, V | undefined]; ``` or ```js /** * @typedef {[D, V | undefined]} Pairs */ ``` Note that in the latter TypeScript-flavor JavaScript example, there is no way for us to firmly distinguish between `D` and `V` as type parameters or as some other identifiers, so we use an algorithm that assumes that any single capital letters are templates. ## Options A single options object has the following properties. ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@template`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ### requireSeparateTemplates Requires that each template have its own separate line, i.e., preventing templates of this format: ```js /** * @template T, U, V */ ``` Defaults to `false`. ||| |---|---| |Context|everywhere| |Tags|`template`| |Recommended|false| |Settings|| |Options|`exemptedBy`, `requireSeparateTemplates`| ## Failing examples The following patterns are considered problems: ````ts /** * */ type Pairs = [D, V | undefined]; // Message: Missing @template D /** * */ export type Pairs = [D, V | undefined]; // Message: Missing @template D /** * @typedef {[D, V | undefined]} Pairs */ // Message: Missing @template D /** * @typedef {[D, V | undefined]} Pairs */ // Settings: {"jsdoc":{"mode":"permissive"}} // Message: Missing @template D /** * @template D, U */ export type Extras = [D, U, V | undefined]; // Message: Missing @template V /** * @template D, U * @typedef {[D, U, V | undefined]} Extras */ // Message: Missing @template V /** * @template D, V */ export type Pairs = [D, V | undefined]; // "jsdoc/require-template": ["error"|"warn", {"requireSeparateTemplates":true}] // Message: Missing separate @template for V /** * @template D, V * @typedef {[D, V | undefined]} Pairs */ // "jsdoc/require-template": ["error"|"warn", {"requireSeparateTemplates":true}] // Message: Missing separate @template for V /** * @template X * @typedef {object} Pairs * @property {D} foo * @property {X} bar */ // Message: Missing @template D /** * */ interface GenericIdentityFn { (arg: Type): Type; } // Message: Missing @template Type /** * */ export interface GenericIdentityFn { (arg: Type): Type; } // Message: Missing @template Type /** * */ export default interface GenericIdentityFn { (arg: Type): Type; } // Message: Missing @template Type /** * */ function identity(arg: Type): Type { return arg; } // Message: Missing @template Type /** * */ export function identity(arg: Type): Type { return arg; } // Message: Missing @template Type /** * */ export default function identity(arg: Type): Type { return arg; } // Message: Missing @template Type /** * */ class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: Missing @template NumType /** * */ export class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: Missing @template NumType /** * */ export default class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: Missing @template NumType /** * */ export default class { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } // Message: Missing @template NumType /** * @callback * @param {[D, V | undefined]} someParam */ // Message: Missing @template D /** * @callback * @returns {[D, V | undefined]} */ // Message: Missing @template D /** * @param bar * @param baz * @returns */ function foo(bar: T, baz: number): T; function foo(bar: T, baz: boolean): T; function foo(bar: T, baz: number | boolean): T { return bar; } // Message: Missing @template T /** * @template */ // Settings: {"jsdoc":{"tagNamePreference":{"template":false}}} // Message: Unexpected tag `@template` ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @template D * @template V */ export type Pairs = [D, V | undefined]; /** * @template D * @template V * @typedef {[D, V | undefined]} Pairs */ /** * @template D, U, V */ export type Extras = [D, U, V | undefined]; /** * @template D, U, V * @typedef {[D, U, V | undefined]} Extras */ /** * @typedef {[D, U, V | undefined]} Extras * @typedef {[D, U, V | undefined]} Extras */ /** * @typedef Foo * @prop {string} bar */ /** * @template D * @template V * @typedef {object} Pairs * @property {D} foo * @property {V} bar */ /** * @template Type */ interface GenericIdentityFn { (arg: Type): Type; } /** * @template Type */ export interface GenericIdentityFn { (arg: Type): Type; } /** * @template Type */ export default interface GenericIdentityFn { (arg: Type): Type; } /** * @template Type */ function identity(arg: Type): Type { return arg; } /** * @template Type */ export function identity(arg: Type): Type { return arg; } /** * @template Type */ export default function identity(arg: Type): Type { return arg; } /** * @template NumType */ class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @template NumType */ export class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @template NumType */ export default class GenericNumber { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @template NumType */ export default class { zeroValue: NumType; add: (x: NumType, y: NumType) => NumType; } /** * @callback * @template D * @template V * @param {[D, V | undefined]} someParam */ /** * @callback * @template D * @template V * @returns {[D, V | undefined]} */ /** * @callback * @returns {[Something | undefined]} */ /** * @template {string | Buffer} [T=string, U=number] * @typedef {object} Dirent * @property {T} name name * @property {U} aNumber number * @property {string} parentPath path */ /** * @type {Something} */ type Pairs = [D, V | undefined]; // "jsdoc/require-template": ["error"|"warn", {"exemptedBy":["type"]}] /** * @inheritdoc * @typedef {[D, V | undefined]} Pairs */ // "jsdoc/require-template": ["error"|"warn", {"exemptedBy":["inheritdoc"]}] /** * Test interface for type definitions. * * @typeParam Foo - dummy type param */ export interface Test { /** * */ bar: Foo; } // Settings: {"jsdoc":{"tagNamePreference":{"template":"typeParam"}}} ```` --- # require-throws-description Requires a description for `@throws` tags. ||| |---|---| |Context|everywhere| |Tags|`throws`| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @throws {SomeType} */ // Message: @throws should have a description ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @throws {SomeType} Has a description */ ```` --- # require-throws-type Requires a type on the `@throws` tag. ||| |---|---| |Context|everywhere| |Tags|`throws`| |Recommended|true| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @throws */ // Message: @throws should have a type ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @throws {SomeType} */ ```` --- # require-throws * [Options](#user-content-require-throws-options) * [`contexts`](#user-content-require-throws-options-contexts) * [`exemptedBy`](#user-content-require-throws-options-exemptedby) * [Context and settings](#user-content-require-throws-context-and-settings) * [Failing examples](#user-content-require-throws-failing-examples) * [Passing examples](#user-content-require-throws-passing-examples) Requires that throw statements are documented. See [this discussion](https://stackoverflow.com/questions/50071115/typescript-promise-rejection-type) on why TypeScript doesn't offer such a feature. Note that since throw statements within async functions end up as rejected `Promise`'s, they are not considered as throw statements for the purposes of this rule. See the `require-rejects` rule for a non-standard way to document `Promise` rejections. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or objects with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@throws`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ## Context and settings | | | | -------- | --- | | Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled | | Tags | `throws` | | Aliases | `exception` | |Recommended|false| | Options |`contexts`, `exemptedBy`| | Settings | `ignoreReplacesDocs`, `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` | ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux (foo) { throw new Error('err') } // Message: Missing JSDoc @throws declaration. /** * */ const quux = function (foo) { throw new Error('err') } // Message: Missing JSDoc @throws declaration. /** * */ const quux = (foo) => { throw new Error('err') } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { while(true) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { do { throw new Error('err') } while(true) } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { for(var i = 0; i <= 10; i++) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { for(num in [1,2,3]) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { for(const num of [1,2,3]) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { for(const index in [1,2,3]) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { with(foo) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { if (true) { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { if (false) { // do nothing } else { throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { try { throw new Error('err') } catch(e) { throw new Error(e.message) } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { try { // do nothing } finally { throw new Error(e.message) } } // Message: Missing JSDoc @throws declaration. /** * */ function quux (foo) { const a = 'b' switch(a) { case 'b': throw new Error('err') } } // Message: Missing JSDoc @throws declaration. /** * @throws */ function quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"throws":false}}} // Message: Unexpected tag `@throws` /** * */ const directThrowAfterArrow = (b) => { const a = () => {}; if (b) { throw new Error('oops') } return a; }; // Message: Missing JSDoc @throws declaration. /** * @throws {never} */ function quux (foo) { throw new Error('err') } // Message: JSDoc @throws declaration set to "never" but throw value found. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @throws An error. */ function quux () { throw new Error('err') } /** * */ function quux (foo) { try { throw new Error('err') } catch(e) {} } /** * @throws {object} */ function quux (foo) { throw new Error('err') } /** * @inheritdoc */ function quux (foo) { throw new Error('err') } /** * @abstract */ function quux (foo) { throw new Error('err') } /** * */ function quux (foo) { } /** * @type {MyCallback} */ function quux () { throw new Error('err') } // "jsdoc/require-throws": ["error"|"warn", {"exemptedBy":["type"]}] /** * */ const itself = (n) => n; /** * Not tracking on nested function */ const nested = () => () => {throw new Error('oops');}; /** */ async function foo() { throw Error("bar"); } /** * @throws {never} */ function quux (foo) { } ```` --- # require-yields-check * [Options](#user-content-require-yields-check-options) * [`checkGeneratorsOnly`](#user-content-require-yields-check-options-checkgeneratorsonly) * [`contexts`](#user-content-require-yields-check-options-contexts) * [`next`](#user-content-require-yields-check-options-next) * [Context and settings](#user-content-require-yields-check-context-and-settings) * [Failing examples](#user-content-require-yields-check-failing-examples) * [Passing examples](#user-content-require-yields-check-passing-examples) Ensures that if a `@yields` is present that a `yield` (or `yield` with a value) is present in the function body (or that if a `@next` is present that there is a `yield` with a return value present). Please also note that JavaScript does allow generators not to have `yield` (e.g., with just a return or even no explicit return), but if you want to enforce that all generators (except wholly empty ones) have a `yield` in the function body, you can use the ESLint [`require-yield`](https://eslint.org/docs/rules/require-yield) rule. In conjunction with this, you can also use the `checkGeneratorsOnly` option as an optimization so that this rule won't need to do its own checking within function bodies. Will also report if multiple `@yields` tags are present. ## Options A single options object has the following properties. ### checkGeneratorsOnly Avoids checking the function body and merely insists that all generators have `@yields`. This can be an optimization with the ESLint `require-yield` rule, as that rule already ensures a `yield` is present in generators, albeit assuming the generator is not empty). Defaults to `false`. ### contexts Set this to an array of strings representing the AST context (or objects with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). ### next If `true`, this option will insist that any use of a (non-standard) `@next` tag (in addition to any `@yields` tag) will be matched by a `yield` which uses a return value in the body of the generator (e.g., `const rv = yield;` or `const rv = yield value;`). This (non-standard) tag is intended to be used to indicate a type and/or description of the value expected to be supplied by the user when supplied to the iterator by its `next` method, as with `it.next(value)` (with the iterator being the `Generator` iterator that is returned by the call to the generator function). This option will report an error if the generator function body merely has plain `yield;` or `yield value;` statements without returning the values. Defaults to `false`. ## Context and settings ||| |---|---| |Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`| |Tags|`yields`| |Aliases|`yield`| |Recommended|true| |Options|`checkGeneratorsOnly`, `contexts`, `next`| ## Failing examples The following patterns are considered problems: ````ts /** * @yields */ function * quux (foo) { } // Message: JSDoc @yields declaration present but yield expression not available in function. /** * @yields */ function quux (foo) { } // "jsdoc/require-yields-check": ["error"|"warn", {"checkGeneratorsOnly":true}] // Message: JSDoc @yields declaration present but yield expression not available in function. /** * @next */ function quux (foo) { } // "jsdoc/require-yields-check": ["error"|"warn", {"checkGeneratorsOnly":true,"next":true}] // Message: JSDoc @next declaration present but yield expression with return value not available in function. /** * @next {SomeType} */ function * quux (foo) { } // "jsdoc/require-yields-check": ["error"|"warn", {"next":true}] // Message: JSDoc @next declaration present but yield expression with return value not available in function. /** * @next {SomeType} */ function * quux (foo) { yield; } // "jsdoc/require-yields-check": ["error"|"warn", {"next":true}] // Message: JSDoc @next declaration present but yield expression with return value not available in function. /** * @next {SomeType} */ function * quux (foo) { yield 5; } // "jsdoc/require-yields-check": ["error"|"warn", {"next":true}] // Message: JSDoc @next declaration present but yield expression with return value not available in function. /** * @yield */ function * quux (foo) { } // Settings: {"jsdoc":{"tagNamePreference":{"yields":"yield"}}} // Message: JSDoc @yield declaration present but yield expression not available in function. /** * @yield-returns {Something} */ function * quux (foo) { yield; } // Settings: {"jsdoc":{"tagNamePreference":{"next":"yield-returns"}}} // "jsdoc/require-yields-check": ["error"|"warn", {"next":true}] // Message: JSDoc @yield-returns declaration present but yield expression with return value not available in function. /** * @yields {undefined} Foo. * @yields {String} Foo. */ function * quux () { yield foo; } // Message: Found more than one @yields declaration. class Foo { /** * @yields {string} */ * bar () { } } // Message: JSDoc @yields declaration present but yield expression not available in function. /** * @yields */ function * quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"yields":false}}} // Message: Unexpected tag `@yields` /** * @next */ function * quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"next":false}}} // "jsdoc/require-yields-check": ["error"|"warn", {"next":true}] // Message: Unexpected tag `@next` /** * @yields {string} */ function * f () { function * g() { yield 'foo' } } // Message: JSDoc @yields declaration present but yield expression not available in function. /** * @yields {Promise} */ async function * quux() {} // Message: JSDoc @yields declaration present but yield expression not available in function. /** * @yields {Promise} */ const quux = async function * () {} // Message: JSDoc @yields declaration present but yield expression not available in function. /** * @yields {never} Foo. */ function * quux () { yield 5; } // Message: JSDoc @yields declaration set with "never" but yield expression is present in function. /** * @next {never} */ function * quux (foo) { const a = yield; } // "jsdoc/require-yields-check": ["error"|"warn", {"next":true}] // Message: JSDoc @next declaration set with "never" but yield expression with return value is present in function. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @yields Foo. */ function * quux () { yield foo; } /** * @yields {string} Foo. */ function * quux () { yield foo; } /** * */ function * quux () { } /** * @yields {undefined} Foo. */ function * quux () {} /** * @yields { void } Foo. */ function quux () {} /** * @yields Foo. * @abstract */ function * quux () { throw new Error('must be implemented by subclass!'); } /** * @yields Foo. * @virtual */ function * quux () { throw new Error('must be implemented by subclass!'); } /** * @yields Foo. * @constructor */ function * quux () { } /** * @interface */ class Foo { /** * @yields {string} */ * bar () { } } /** * @record */ class Foo { /** * @yields {string} */ * bar () { } } // Settings: {"jsdoc":{"mode":"closure"}} /** * @yields {undefined} Foo. */ function * quux () { } /** * @yields {void} Foo. */ function * quux () { } /** * @yields {never} Foo. */ function * quux () { } /** * @yields {void} Foo. */ function * quux () { yield undefined; } /** * @yields {void} Foo. */ function * quux () { yield; } /** * */ function * quux () { yield undefined; } /** * */ function * quux () { yield; } /** * @yields {true} */ function * quux () { try { yield true; } catch (err) { } yield; } /** * @yields {true} */ function * quux () { try { } finally { yield true; } yield; } /** * @yields {true} */ function * quux () { try { yield; } catch (err) { } yield true; } /** * @yields {true} */ function * quux () { try { something(); } catch (err) { yield true; } yield; } /** * @yields {true} */ function * quux () { switch (true) { case 'abc': yield true; } yield; } /** * @yields {true} */ function * quux () { switch (true) { case 'abc': yield; } yield true; } /** * @yields {true} */ function * quux () { for (const i of abc) { yield true; } yield; } /** * @yields {true} */ function * quux () { for (const a in b) { yield true; } } /** * @yields {true} */ function * quux () { for (let i=0; i # require-yields-description Requires a description for `@yields` tags. ||| |---|---| |Context|everywhere| |Tags|`yields`| |Recommended|false| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @yields {SomeType} */ // Message: @yields should have a description ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @yields {SomeType} Has a description */ /** * @yields * The results. */ export function *test1(): IterableIterator { yield "hello"; } ```` --- # require-yields-type Requires a type on the `@yields` tag. ||| |---|---| |Context|everywhere| |Tags|`yields`| |Recommended|true| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @yields */ // Message: @yields should have a type /** * @yield */ // Message: @yields should have a type ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @yields {SomeType} */ ```` --- # require-yields * [Options](#user-content-require-yields-options) * [`contexts`](#user-content-require-yields-options-contexts) * [`exemptedBy`](#user-content-require-yields-options-exemptedby) * [`forceRequireNext`](#user-content-require-yields-options-forcerequirenext) * [`forceRequireYields`](#user-content-require-yields-options-forcerequireyields) * [`next`](#user-content-require-yields-options-next) * [`nextWithGeneratorTag`](#user-content-require-yields-options-nextwithgeneratortag) * [`withGeneratorTag`](#user-content-require-yields-options-withgeneratortag) * [Context and settings](#user-content-require-yields-context-and-settings) * [Failing examples](#user-content-require-yields-failing-examples) * [Passing examples](#user-content-require-yields-passing-examples) Requires that yields are documented. Will also report if multiple `@yields` tags are present. See the `next`, `forceRequireNext`, and `nextWithGeneratorTag` options for an option to expect a non-standard `@next` tag. ## Options A single options object has the following properties. ### contexts Set this to an array of strings representing the AST context (or objects with optional `context` and `comment` properties) where you wish the rule to be applied. `context` defaults to `any` and `comment` defaults to no specific comment context. Overrides the default contexts (`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`). Set to `"any"` if you want the rule to apply to any JSDoc block throughout your files (as is necessary for finding function blocks not attached to a function declaration or expression, i.e., `@callback` or `@function` (or its aliases `@func` or `@method`) (including those associated with an `@interface`). This rule will only apply on non-default contexts when there is such a tag present and the `forceRequireYields` option is set or if the `withGeneratorTag` option is set with a present `@generator` tag (since we are not checking against the actual `yield` values in these cases). ### exemptedBy Array of tags (e.g., `['type']`) whose presence on the document block avoids the need for a `@yields`. Defaults to an array with `inheritdoc`. If you set this array, it will overwrite the default, so be sure to add back `inheritdoc` if you wish its presence to cause exemption of the rule. ### forceRequireNext Set to `true` to always insist on `@next` documentation even if there are no `yield` statements in the function or none return values. May be desired to flag that a project is aware of the expected yield return being `undefined`. Defaults to `false`. ### forceRequireYields Set to `true` to always insist on `@yields` documentation for generators even if there are only expressionless `yield` statements in the function. May be desired to flag that a project is aware of an `undefined`/`void` yield. Defaults to `false`. ### next If `true`, this option will insist that any use of a `yield` return value (e.g., `const rv = yield;` or `const rv = yield value;`) has a (non-standard) `@next` tag (in addition to any `@yields` tag) so as to be able to document the type expected to be supplied into the iterator (the `Generator` iterator that is returned by the call to the generator function) to the iterator (e.g., `it.next(value)`). The tag will not be expected if the generator function body merely has plain `yield;` or `yield value;` statements without returning the values. Defaults to `false`. ### nextWithGeneratorTag If a `@generator` tag is present on a block, require (non-standard ) `@next` (see `next` option). This will require using `void` or `undefined` in cases where generators do not use the `next()`-supplied incoming `yield`-returned value. Defaults to `false`. See `contexts` to `any` if you want to catch `@generator` with `@callback` or such not attached to a function. ### withGeneratorTag If a `@generator` tag is present on a block, require `@yields`/`@yield`. Defaults to `true`. See `contexts` to `any` if you want to catch `@generator` with `@callback` or such not attached to a function. ## Context and settings ||| |---|---| |Context|Generator functions (`FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled)| |Tags|`yields`| |Aliases|`yield`| |Recommended|true| | Options |`contexts`, `exemptedBy`, `forceRequireNext`, `forceRequireYields`, `next`, `nextWithGeneratorTag`, `withGeneratorTag`| | Settings | `ignoreReplacesDocs`, `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` | ## Failing examples The following patterns are considered problems: ````ts /** * */ function * quux (foo) { yield foo; } // Message: Missing JSDoc @yields declaration. /** * @yields */ function * quux (foo) { const retVal = yield foo; } // "jsdoc/require-yields": ["error"|"warn", {"next":true}] // Message: Missing JSDoc @next declaration. /** * @yields */ function * quux (foo) { const retVal = yield; } // "jsdoc/require-yields": ["error"|"warn", {"next":true}] // Message: Missing JSDoc @next declaration. /** * @yields {void} */ function * quux () { } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireNext":true}] // Message: Missing JSDoc @next declaration. /** * @yields {void} */ function * quux () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireNext":true}] // Message: Missing JSDoc @next declaration. /** * */ function * quux (foo) { const a = yield foo; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux (foo) { yield foo; } // Settings: {"jsdoc":{"tagNamePreference":{"yields":"yield"}}} // Message: Missing JSDoc @yield declaration. /** * @yields */ function * quux (foo) { const val = yield foo; } // Settings: {"jsdoc":{"tagNamePreference":{"next":"yield-returns"}}} // "jsdoc/require-yields": ["error"|"warn", {"next":true}] // Message: Missing JSDoc @yield-returns declaration. /** * @yields * @next */ function * quux () { const ret = yield 5; } // Settings: {"jsdoc":{"tagNamePreference":{"next":false}}} // "jsdoc/require-yields": ["error"|"warn", {"next":true}] // Message: Unexpected tag `@next` /** * */ function * quux() { yield 5; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * */ function * quux() { yield; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * */ const quux = async function * () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * */ async function * quux () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * @function * @generator */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * @callback * @generator */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * @yields {undefined} * @yields {void} */ function * quux (foo) { return foo; } // Message: Found more than one @yields declaration. /** * @yields */ function * quux () { } // Settings: {"jsdoc":{"tagNamePreference":{"yields":false}}} // Message: Unexpected tag `@yields` /** * @param foo */ function * quux (foo) { yield 'bar'; } // "jsdoc/require-yields": ["error"|"warn", {"exemptedBy":["notPresent"]}] // Message: Missing JSDoc @yields declaration. /** * @param {array} a */ async function * foo(a) { return; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * @param {array} a */ async function * foo(a) { yield Promise.all(a); } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. class quux { /** * */ * quux () { yield; } } // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"forceRequireYields":true}] // Message: Missing JSDoc @yields declaration. /** * @param {array} a */ async function * foo(a) { yield Promise.all(a); } // Message: Missing JSDoc @yields declaration. /** * @generator */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"withGeneratorTag":true}] // Message: Missing JSDoc @yields declaration. /** * @generator * @yields */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"nextWithGeneratorTag":true}] // Message: Missing JSDoc @next declaration. /** * */ function * quux () { if (true) { yield; } yield true; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { try { yield true; } catch (err) { } yield; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { try { } finally { yield true; } yield; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { try { yield; } catch (err) { } yield true; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { try { something(); } catch (err) { yield true; } yield; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { switch (true) { case 'abc': yield true; } yield; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { switch (true) { case 'abc': yield; } yield true; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { for (const i of abc) { yield true; } yield; } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { for (const a in b) { yield true; } } // Message: Missing JSDoc @yields declaration. /** * */ function * quux () { for (let i=0; i ## Passing examples The following patterns are not considered problems: ````ts /** * @yields Foo. */ function * quux () { yield foo; } /** * @yields Foo. */ function * quux () { yield foo; } // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"]}] /** * */ function * quux () { } /** * */ function * quux () { yield; } /** * */ function quux (bar) { bar.doSomething(function * (baz) { yield baz.corge(); }) } /** * @yields {Array} */ function * quux (bar) { yield bar.doSomething(function * (baz) { yield baz.corge(); }) } /** * @inheritdoc */ function * quux (foo) { } /** * @override */ function * quux (foo) { } /** * @constructor */ function * quux (foo) { } /** * @implements */ function * quux (foo) { yield; } /** * @override */ function * quux (foo) { yield foo; } /** * @class */ function * quux (foo) { yield foo; } /** * @yields {object} */ function * quux () { yield {a: foo}; } /** * @yields {void} */ function * quux () { } /** * @yields {undefined} */ function * quux () { } /** * @yields {void} */ function quux () { } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** * @yields {void} * @next {void} */ function * quux () { } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireNext":true}] /** * @yields {void} */ function * quux () { yield undefined; } /** * @yields {void} */ function * quux () { yield undefined; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** * @yields {void} */ function * quux () { yield; } /** * @yields {void} */ function * quux () { } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** * @yields {void} */ function * quux () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** @type {SpecialIterator} */ function * quux () { yield 5; } /** * @yields {Something} */ async function * quux () { } // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** * */ async function * quux () {} /** * */ const quux = async function * () {} /** * @type {MyCallback} */ function * quux () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"exemptedBy":["type"]}] /** * @param {array} a */ async function * foo (a) { yield; } /** * */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"]}] /** * @function */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"]}] /** * @function */ // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** * @callback */ // "jsdoc/require-yields": ["error"|"warn", {"forceRequireYields":true}] /** * @generator */ // "jsdoc/require-yields": ["error"|"warn", {"withGeneratorTag":true}] /** * @generator */ // "jsdoc/require-yields": ["error"|"warn", {"nextWithGeneratorTag":true}] /** * @generator * @yields */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"withGeneratorTag":true}] /** * @generator * @yields * @next */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"nextWithGeneratorTag":true}] /** * @generator */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"withGeneratorTag":false}] /** * @generator * @yields */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"nextWithGeneratorTag":false}] /** * @yields */ function * quux (foo) { const a = yield foo; } /** * @yields * @next */ function * quux (foo) { let a = yield; } // "jsdoc/require-yields": ["error"|"warn", {"next":true}] /** * @yields * @next */ function * quux (foo) { const a = yield foo; } // "jsdoc/require-yields": ["error"|"warn", {"next":true}] /** * */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"nextWithGeneratorTag":true}] /** * */ // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"next":true}] /** * */ function quux () {} // "jsdoc/require-yields": ["error"|"warn", {"contexts":["any"],"next":true}] /** * @yields {void} */ function * quux () { yield; } // "jsdoc/require-yields": ["error"|"warn", {"next":true}] /** * */ function * quux (foo) { const a = function * bar () { yield foo; } } /** * */ export { foo } from "bar" // "jsdoc/require-yields": ["error"|"warn", {"contexts":["ExportNamedDeclaration"]}] ```` --- # required-tags Requires tags be present, optionally for specific contexts. ## Options A single options object has the following properties. ### tags May be an array of either strings or objects with a string `tag` property and `context` string property. ||| |---|---| |Context|everywhere| |Tags|(Any)| |Recommended|false| |Settings|| |Options|`tags`| ## Failing examples The following patterns are considered problems: ````ts /** * */ function quux () {} // "jsdoc/required-tags": ["error"|"warn", {"tags":["see"]}] // Message: Missing required tag "see" /** * */ function quux () {} // "jsdoc/required-tags": ["error"|"warn", {"tags":[{"context":"FunctionDeclaration","tag":"see"}]}] // Message: Missing required tag "see" /** * @type {SomeType} */ function quux () {} // "jsdoc/required-tags": ["error"|"warn", {"tags":[{"context":"FunctionDeclaration","tag":"see"}]}] // Message: Missing required tag "see" /** * @type {SomeType} */ function quux () {} // Message: Rule `required-tags` is missing a `tags` option. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @see */ function quux () {} // "jsdoc/required-tags": ["error"|"warn", {"tags":["see"]}] /** * */ class Quux {} // "jsdoc/required-tags": ["error"|"warn", {"tags":[{"context":"FunctionDeclaration","tag":"see"}]}] ```` --- # sort-tags * [Fixer](#user-content-sort-tags-fixer) * [Options](#user-content-sort-tags-options) * [`alphabetizeExtras`](#user-content-sort-tags-options-alphabetizeextras) * [`linesBetween`](#user-content-sort-tags-options-linesbetween) * [`reportIntraTagGroupSpacing`](#user-content-sort-tags-options-reportintrataggroupspacing) * [`reportTagGroupSpacing`](#user-content-sort-tags-options-reporttaggroupspacing) * [`tagExceptions`](#user-content-sort-tags-options-tagexceptions) * [`tagSequence`](#user-content-sort-tags-options-tagsequence) * [Context and settings](#user-content-sort-tags-context-and-settings) * [Failing examples](#user-content-sort-tags-failing-examples) * [Passing examples](#user-content-sort-tags-passing-examples) Sorts tags by a specified sequence according to tag name, optionally adding line breaks between tag groups. (Default order originally inspired by [`@homer0/prettier-plugin-jsdoc`](https://github.com/homer0/packages/tree/main/packages/public/prettier-plugin-jsdoc).) Optionally allows adding line breaks between tag groups and/or between tags within a tag group. Please note: unless you are disabling reporting of line breaks, this rule should not be used with the default "never" or "always" options of `tag-lines` (a rule enabled by default with the recommended config) as that rule adds its own line breaks after tags and may interfere with any line break setting this rule will attempt to do when not disabled. You may, however, safely set the "any" option in that rule along with `startLines` and/or `endLines`. ## Fixer Sorts tags by a specified sequence according to tag name, optionally adding line breaks between tag groups. ## Options A single options object has the following properties. ### alphabetizeExtras Defaults to `false`. Alphabetizes any items not within `tagSequence` after any items within `tagSequence` (or in place of the special `-other` pseudo-tag) are sorted. If you want all your tags alphabetized, you can supply an empty array for `tagSequence` along with setting this option to `true`. ### linesBetween Indicates the number of lines to be added between tag groups. Defaults to 1. Do not set to 0 or 2+ if you are using `tag-lines` and `"always"` and do not set to 1+ if you are using `tag-lines` and `"never"`. ### reportIntraTagGroupSpacing Whether to enable reporting and fixing of line breaks within tags of a given tag group. Defaults to `true` which will remove any line breaks at the end of such tags. Do not use with `true` if you are using `tag-lines` and `always`. ### reportTagGroupSpacing Whether to enable reporting and fixing of line breaks between tag groups as set by `linesBetween`. Defaults to `true`. Note that the very last tag will not have spacing applied regardless. For adding line breaks there, you may wish to use the `endLines` option of the `tag-lines` rule. ### tagExceptions Allows specification by tag of a specific higher maximum number of lines. Keys are tags and values are the maximum number of lines allowed for such tags. Overrides `linesBetween`. Defaults to no special exceptions per tag. ### tagSequence An array of tag group objects indicating the preferred sequence for sorting tags. Each item in the array should be an object with a `tags` property set to an array of tag names. Tag names earlier in the list will be arranged first. The relative position of tags of the same name will not be changed. Earlier groups will also be arranged before later groups, but with the added feature that additional line breaks may be added between (or before or after) such groups (depending on the setting of `linesBetween`). Tag names not in the list will be grouped together at the end. The pseudo-tag `-other` can be used to place them anywhere else if desired. The tags will be placed in their order of appearance, or alphabetized if `alphabetizeExtras` is enabled, see more below about that option. Defaults to the array below (noting that it is just a single tag group with no lines between groups by default). Please note that this order is still experimental, so if you want to retain a fixed order that doesn't change into the future, supply your own `tagSequence`. ```js [{tags: [ // Brief descriptions 'summary', 'typeSummary', // Module/file-level 'module', 'exports', 'file', 'fileoverview', 'overview', 'import', // Identifying (name, type) 'typedef', 'interface', 'record', 'template', 'name', 'kind', 'type', 'alias', 'external', 'host', 'callback', 'func', 'function', 'method', 'class', 'constructor', // Relationships 'modifies', 'mixes', 'mixin', 'mixinClass', 'mixinFunction', 'namespace', 'borrows', 'constructs', 'lends', 'implements', 'requires', // Long descriptions 'desc', 'description', 'classdesc', 'tutorial', 'copyright', 'license', // Simple annotations 'const', 'constant', 'final', 'global', 'readonly', 'abstract', 'virtual', 'var', 'member', 'memberof', 'memberof!', 'inner', 'instance', 'inheritdoc', 'inheritDoc', 'override', 'hideconstructor', // Core function/object info 'param', 'arg', 'argument', 'prop', 'property', 'return', 'returns', // Important behavior details 'async', 'generator', 'default', 'defaultvalue', 'enum', 'augments', 'extends', 'throws', 'exception', 'yield', 'yields', 'event', 'fires', 'emits', 'listens', 'this', // Access 'static', 'private', 'protected', 'public', 'access', 'package', '-other', // Supplementary descriptions 'see', 'example', // METADATA // Other Closure (undocumented) metadata 'closurePrimitive', 'customElement', 'expose', 'hidden', 'idGenerator', 'meaning', 'ngInject', 'owner', 'wizaction', // Other Closure (documented) metadata 'define', 'dict', 'export', 'externs', 'implicitCast', 'noalias', 'nocollapse', 'nocompile', 'noinline', 'nosideeffects', 'polymer', 'polymerBehavior', 'preserve', 'struct', 'suppress', 'unrestricted', // @homer0/prettier-plugin-jsdoc metadata 'category', // Non-Closure metadata 'ignore', 'author', 'version', 'variation', 'since', 'deprecated', 'todo', ]}]; ``` A single options object has the following properties. ##### tags See description on `tagSequence`. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|any| |Recommended|false| |Settings|| |Options|`alphabetizeExtras`, `linesBetween`, `reportIntraTagGroupSpacing`, `reportTagGroupSpacing`, `tagExceptions`, `tagSequence`| ## Failing examples The following patterns are considered problems: ````ts /** * @returns {string} * @param b * @param a */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * Some description * @returns {string} * @param b * @param a */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @returns {string} * @param b A long * description * @param a */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * Some description * @returns {string} * @param b A long * description * @param a */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @param b A long * description * @returns {string} * @param a */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @typedef Foo * @template {Object} T * @prop {T} bar */ // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @def * @xyz * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"alphabetizeExtras":true}] // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @xyz * @def * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["def","xyz","abc"]}]}] // Message: Tags are not in the prescribed order: def, xyz, abc /** * @xyz * @def * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["def","xyz"]},{"tags":["abc"]}]}] // Message: Tags are not in the prescribed order: def, xyz, abc /** * @returns {string} * @ignore * @param b A long * description * @param a * @module */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @xyz * @abc * @abc * @def * @xyz */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"alphabetizeExtras":true}] // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @param b A long * description * @module */ function quux () {} // Message: Tags are not in the prescribed order: summary, typeSummary, module, exports, file, fileoverview, overview, import, template, typedef, interface, record, name, kind, type, alias, external, host, callback, func, function, method, class, constructor, modifies, mixes, mixin, mixinClass, mixinFunction, namespace, borrows, constructs, lends, implements, requires, desc, description, classdesc, tutorial, copyright, license, internal, overload, const, constant, final, global, readonly, abstract, virtual, var, member, memberof, memberof!, inner, instance, inheritdoc, inheritDoc, override, hideconstructor, param, arg, argument, prop, property, return, returns, async, generator, default, defaultvalue, enum, augments, extends, throws, exception, yield, yields, event, fires, emits, listens, this, satisfies, static, private, protected, public, access, package, -other, see, example, closurePrimitive, customElement, expose, hidden, idGenerator, meaning, ngInject, owner, wizaction, define, dict, export, externs, implicitCast, noalias, nocollapse, nocompile, noinline, nosideeffects, polymer, polymerBehavior, preserve, struct, suppress, unrestricted, category, ignore, author, version, variation, since, deprecated, todo /** * @def * @xyz * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":2,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] // Message: Tag groups do not have the expected whitespace /** * @def * @xyz * * * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":1,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] // Message: Tag groups do not have the expected whitespace /** * @def * @xyz A multiline * description * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":2,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] // Message: Tag groups do not have the expected whitespace /** * @def * @xyz * @xyz * * * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":1,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] // Message: Tag groups do not have the expected whitespace /** * Foo * * @param {( * req: express.Request, * done: (error: any, user?: any, info?: any) => void * ) => void} verify - callback to excute custom authentication logic * @see https://github.com/jaredhanson/passport/blob/v0.4.1/lib/middleware/authenticate.js#L217 * */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["since","access"]},{"tags":["class","augments","mixes"]},{"tags":["alias","memberof"]},{"tags":["see","link","global"]},{"tags":["fires","listens"]},{"tags":["param"]},{"tags":["yields"]},{"tags":["returns"]}]}] // Message: Tags are not in the prescribed order: since, access, class, augments, mixes, alias, memberof, see, link, global, fires, listens, param, yields, returns /** * Summary. (use period) * * Description. (use period) * * @since 1.0.1 * @access private * * @class * @mixes mixin * * @alias realName * @memberof namespace * * @see Function/class relied on * @global * * @tutorial Asd * @license MIT * * @fires eventName * @fires className#eventName * @listens event:eventName * @listens className~event:eventName * * @tutorial Asd * @license MIT * * @yields {string} Yielded value description. * * @param {string} var1 - Description. * @param {string} var2 - Description of optional variable. * @param {string} var3 - Description of optional variable with default variable. * @param {object} objectVar - Description. * @param {string} objectVar.key - Description of a key in the objectVar parameter. * * @returns {string} Return value description. */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["since","access"]},{"tags":["class","augments","mixes"]},{"tags":["alias","memberof"]},{"tags":["see","link","global"]},{"tags":["fires","listens"]},{"tags":["param"]},{"tags":["yields"]},{"tags":["returns"]}]}] // Message: Tags are not in the prescribed order: since, access, class, augments, mixes, alias, memberof, see, link, global, fires, listens, param, yields, returns /** * @def * @zzz * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":1,"tagSequence":[{"tags":["qrs"]},{"tags":["def","-other","xyz"]},{"tags":["abc"]}]}] // Message: Tag groups do not have the expected whitespace /** * @xyz * @def * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"alphabetizeExtras":true,"tagSequence":[]}] // Message: Tags are not in the prescribed order: (alphabetical) /** * @example * enum Color { Red, Green, Blue } * faker.helpers.enumValue(Color) // 1 (Green) * * enum Direction { North = 'North', South = 'South'} * faker.helpers.enumValue(Direction) // 'South' * * enum HttpStatus { Ok = 200, Created = 201, BadRequest = 400, Unauthorized = 401 } * faker.helpers.enumValue(HttpStatus) // 200 (Ok) * @since 8.0.0 */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["internal"]},{"tags":["template","param"]},{"tags":["returns"]},{"tags":["throws"]},{"tags":["see"]},{"tags":["example"]},{"tags":["since"]},{"tags":["deprecated"]}]}] // Message: Tag groups do not have the expected whitespace /** * @param b * @param a * @returns {string} * @example abc * * * @example def */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":0,"tagExceptions":{"example":1}}] // Message: Intra-group tags have unexpected whitespace ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param b * @param a * @returns {string} */ function quux () {} /** * @abc * @def * @xyz */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"alphabetizeExtras":true}] /** * @def * @xyz * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"alphabetizeExtras":false}] /** * @def * @xyz * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["def","xyz","abc"]}]}] /** @def */ function quux () {} /** * @def * @xyz * * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":1,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] /** * @def * @xyz A multiline * description * * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":1,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] /** * Foo * * @see https://github.com/jaredhanson/passport/blob/v0.4.1/lib/middleware/authenticate.js#L217 * * @param {( * req: express.Request, * done: (error: any, user?: any, info?: any) => void * ) => void} verify - callback to excute custom authentication logic */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["since","access"]},{"tags":["class","augments","mixes"]},{"tags":["alias","memberof"]},{"tags":["see","link","global"]},{"tags":["fires","listens"]},{"tags":["param"]},{"tags":["yields"]},{"tags":["returns"]}]}] /** * Constructor. * * @public * * @param {string} [message] - Error message. */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["since","access"]},{"tags":["class","augments","mixes"]},{"tags":["alias","memberof"]},{"tags":["public","protected","private","override"]},{"tags":["override","async"]},{"tags":["see","link","global"]},{"tags":["param"]},{"tags":["yields"]},{"tags":["returns"]},{"tags":["fires","-other","listens"]}]}] /** * @param options.mode The mode to generate the birthdate. Supported modes are `'age'` and `'year'` . * * There are two modes available `'age'` and `'year'`: * - `'age'`: The min and max options define the age of the person (e.g. `18` - `42`). * - `'year'`: The min and max options define the range the birthdate may be in (e.g. `1900` - `2000`). * * Defaults to `year`. * * @example */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["internal"]},{"tags":["template","param"]},{"tags":["returns"]},{"tags":["throws"]},{"tags":["see"]},{"tags":["example"]},{"tags":["since"]},{"tags":["deprecated"]}]}] /** * @example * enum Color { Red, Green, Blue } * faker.helpers.enumValue(Color) // 1 (Green) * * enum Direction { North = 'North', South = 'South'} * faker.helpers.enumValue(Direction) // 'South' * * enum HttpStatus { Ok = 200, Created = 201, BadRequest = 400, Unauthorized = 401 } * faker.helpers.enumValue(HttpStatus) // 200 (Ok) * * @since 8.0.0 */ // "jsdoc/sort-tags": ["error"|"warn", {"tagSequence":[{"tags":["internal"]},{"tags":["template","param"]},{"tags":["returns"]},{"tags":["throws"]},{"tags":["see"]},{"tags":["example"]},{"tags":["since"]},{"tags":["deprecated"]}]}] /** * @def * @xyz * @abc */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":2,"reportTagGroupSpacing":false,"tagSequence":[{"tags":["qrs"]},{"tags":["def","xyz"]},{"tags":["abc"]}]}] /** * @param b * @param a * @returns {string} * @example abc * * @example def */ function quux () {} // "jsdoc/sort-tags": ["error"|"warn", {"linesBetween":0,"tagExceptions":{"example":1}}] ```` --- # tag-lines * [Fixer](#user-content-tag-lines-fixer) * [Options](#user-content-tag-lines-options) * [`applyToEndTag`](#user-content-tag-lines-options-applytoendtag) * [`count`](#user-content-tag-lines-options-count) * [`endLines`](#user-content-tag-lines-options-endlines) * [`maxBlockLines`](#user-content-tag-lines-options-maxblocklines) * [`startLines`](#user-content-tag-lines-options-startlines) * [`tags`](#user-content-tag-lines-options-tags) * [Context and settings](#user-content-tag-lines-context-and-settings) * [Failing examples](#user-content-tag-lines-failing-examples) * [Passing examples](#user-content-tag-lines-passing-examples) Enforces lines (or no lines) between tags. If you only want lines preceding all tags or after all tags, you can use the "any" option along with `startLines` and/or `endLines`. The "always" or "never" options of this rule should not be used with the linebreak-setting options of the `sort-tags` rule as both may try to impose a conflicting number of lines. ## Fixer Removes or adds lines between tags or trailing tags. ## Options The first option is a string with the following possible values: "always", "any", "never". Defaults to "never". "any" is only useful with `tags` (allowing non-enforcement of lines except for particular tags) or with `startLines`, `endLines`, or `maxBlockLines`. It is also necessary if using the linebreak-setting options of the `sort-tags` rule so that the two rules won't conflict in both attempting to set lines between tags. The next option is an object with the following properties. ### applyToEndTag Set to `false` and use with "always" to indicate the normal lines to be added after tags should not be added after the final tag. Defaults to `true`. ### count Use with "always" to indicate the number of lines to require be present. Defaults to 1. ### endLines If not set to `null`, will enforce end lines to the given count on the final tag only. Defaults to `0`. ### maxBlockLines If not set to `null`, will enforce a maximum number of lines to the given count anywhere in the block description. Note that if non-`null`, `maxBlockLines` must be greater than or equal to `startLines`. Defaults to `null`. ### startLines If not set to `null`, will enforce end lines to the given count before the first tag only, unless there is only whitespace content, in which case, a line count will not be enforced. Defaults to `0`. ### tags Overrides the default behavior depending on specific tags. An object whose keys are tag names and whose values are objects with the following keys: 1. `lines` - Set to `always`, `never`, or `any` to override. 2. `count` - Overrides main `count` (for "always") Defaults to empty object. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|Any| |Recommended|true| |Settings|N/A| |Options|string ("always", "any", "never") followed by object with `applyToEndTag`, `count`, `endLines`, `maxBlockLines`, `startLines`, `tags`| ## Failing examples The following patterns are considered problems: ````ts /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always"] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"count":2}] // Message: Expected 2 lines between tags but found 0 /** * Some description * @param {string} a * * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"count":2}] // Message: Expected 2 lines between tags but found 1 /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"applyToEndTag":false}] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {string} a * * @param {number} b * */ // "jsdoc/tag-lines": ["error"|"warn", "never"] // Message: Expected no lines between tags /** * Some description * @param {string} a * * @param {number} b * */ // Message: Expected no lines between tags /** * Some description * @param {string} a * * @param {number} b * @param {number} c */ // "jsdoc/tag-lines": ["error"|"warn", "always"] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"tags":{"param":{"lines":"always"}}}] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {string} a * @param {number} b * */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"tags":{"param":{"lines":"never"}}}] // Message: Expected no lines between tags /** * Some description * @param {string} a * * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"count":2,"tags":{"param":{"lines":"always"}}}] // Message: Expected 2 lines between tags but found 1 /** * Some description * @param {string} a * * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"count":5,"tags":{"param":{"count":2,"lines":"always"}}}] // Message: Expected 2 lines between tags but found 1 /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"tags":{"anotherTag":{"lines":"never"}}}] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {string} A broken up * * tag description. * @param {number} b * */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"endLines":null}] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {number} b * * @returns {string} A broken up * * tag description. */ // "jsdoc/tag-lines": ["error"|"warn", "always"] // Message: Expected 1 line between tags but found 0 /** * Some description * @param {string} a * @param {string} b * * @returns {SomeType} An extended * description. * * This is still part of `@returns`. * */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"endLines":0}] // Message: Expected 0 trailing lines /** * Some description * @param {string} a * @param {string} b * * @returns {SomeType} An extended * description. * * This is still part of `@returns`. * * * */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"endLines":1}] // Message: Expected 1 trailing lines /** * Some description * @param {string} a * @param {string} b * * @returns {SomeType} An extended * description. * * This is still part of `@returns`. * */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"endLines":2}] // Message: Expected 2 trailing lines /** * Some description * * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}] // Message: Expected only 1 line after block description /** * Some description * * * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":2}] // Message: Expected only 2 lines after block description /** * Some description * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":0}] // Message: Expected only 0 lines after block description /** * Some description * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":2}] // Message: Expected 2 lines after block description /** * Some description * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}] // Message: Expected 1 lines after block description /** * * Some description * * Abc * * * * Def * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"maxBlockLines":2}] // Message: Expected a maximum of 2 lines within block description /** * * Some description * * Abc * * * * Def * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"maxBlockLines":1}] // Message: Expected a maximum of 1 line within block description /** * * Some description * * Abc * * * * Def * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"maxBlockLines":0}] // Message: Expected a maximum of 0 lines within block description /** * * Some description * * Abc * * * Def * * * * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"maxBlockLines":2,"startLines":5}] // Message: If set to a number, `maxBlockLines` must be greater than or equal to `startLines`. /** * My Test Function, with some example code. * * ```js * new Foo(); * ``` * * * @param {string} bar */ function myTestFunction(bar) { } // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}] // Message: Expected only 1 line after block description /** * * Second Test Case * @param {number} baz * */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}] // Message: Expected 1 lines after block description ```` ## Passing examples The following patterns are not considered problems: ````ts /** * Some description * @param {string} a * @param {number} b */ /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never"] /** * @param {string} a * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"applyToEndTag":false}] /** * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"applyToEndTag":false}] /** @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"applyToEndTag":false}] /** * Some description * @param {string} a * * @param {number} b * */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"endLines":null}] /** * Some description * @param {string} a * * * @param {number} b * * */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"count":2,"endLines":null}] /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"tags":{"param":{"lines":"any"}}}] /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"tags":{"param":{"lines":"any"}}}] /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"tags":{"param":{"lines":"never"}}}] /** * Some description * @param {number} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"tags":{"param":{"lines":"any"}}}] /** * Some description * @param {number} a * * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"tags":{"param":{"lines":"any"}}}] /** * Some description * @param {number} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"tags":{"param":{"lines":"never"}}}] /** * Some description * @param {string} a * * * @param {number} b * * */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"count":5,"tags":{"param":{"count":2,"lines":"always"}}}] /** * Some description * @param {string} a * @param {number} b */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"tags":{"anotherTag":{"lines":"always"}}}] /** * Some description * @param {string} a * * This is still part of `@param`. * @returns {SomeType} An extended * description. */ // "jsdoc/tag-lines": ["error"|"warn", "never"] /** * Some description * @param {string} a * @returns {SomeType} An extended * description. * * This is still part of `@returns`. */ // "jsdoc/tag-lines": ["error"|"warn", "never"] /** * Some description * @param {string} a * * This is still part of `@param`. * * @returns {SomeType} An extended * description. * */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"endLines":null}] /** * Some description * @param {string} a * * @returns {SomeType} An extended * description. * * This is still part of `@returns`. * */ // "jsdoc/tag-lines": ["error"|"warn", "always",{"endLines":null}] /** * Some description * @param {string} a * @param {string} b * * @returns {SomeType} An extended * description. * * This is still part of `@returns`. */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"endLines":0}] /** * Some description * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}] /** * Some description * @param {string} a * */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"endLines":1}] /** * Some description * * * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"startLines":null}] /** * Some description * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "never",{"startLines":null}] /** * @param {string} input */ function processSass (input) { } // "jsdoc/tag-lines": ["error"|"warn", "never",{"startLines":1}] /** * * @param {string} input */ function processSass (input) { } // "jsdoc/tag-lines": ["error"|"warn", "never",{"startLines":1}] /** * Toggles the deselect all icon button action */ function updateIconButton () { } // "jsdoc/tag-lines": ["error"|"warn", "never",{"startLines":1}] /** A class. */ class _Foo { /** @param arg Argument. */ conststructor(arg: string) { console.log(arg); } } // "jsdoc/tag-lines": ["error"|"warn", "any",{"startLines":1}] /** * * Some description * * Abc * * * Def * @param {string} a */ // "jsdoc/tag-lines": ["error"|"warn", "any",{"maxBlockLines":2}] ```` --- # text-escaping * [Fixer](#user-content-text-escaping-fixer) * [Options](#user-content-text-escaping-options) * [`escapeHTML`](#user-content-text-escaping-options-escapehtml) * [`escapeMarkdown`](#user-content-text-escaping-options-escapemarkdown) * [Context and settings](#user-content-text-escaping-context-and-settings) * [Failing examples](#user-content-text-escaping-failing-examples) * [Passing examples](#user-content-text-escaping-passing-examples) This rule can auto-escape certain characters that are input within block and tag descriptions. This rule may be desirable if your text is known not to contain HTML or Markdown and you therefore do not wish for it to be accidentally interpreted as such by the likes of Visual Studio Code or if you wish to view it escaped within it or your documentation. `@example` tag content will not be checked. ## Fixer Auto-escapes certain HTML or Markdown characters that are input within block and tag descriptions. ## Options A single options object has the following properties. ### escapeHTML This option escapes all `<` and `&` characters (except those followed by whitespace which are treated as literals by Visual Studio Code). Defaults to `false`. ### escapeMarkdown This option escapes the first backtick (`` ` ``) in a paired sequence. Defaults to `false`. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|false| |Settings|| |Options|`escapeHTML`, `escapeMarkdown`| ## Failing examples The following patterns are considered problems: ````ts /** * Some things to escape: and > and `test` */ // Message: You must include either `escapeHTML` or `escapeMarkdown` /** * Some things to escape: and > and ઼ and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] // Message: You have unescaped HTML characters < or & /** * Some things to escape: and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] // Message: You have unescaped Markdown backtick sequences /** * Some things to escape: * and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] // Message: You have unescaped HTML characters < or & /** * Some things to escape: * and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] // Message: You have unescaped Markdown backtick sequences /** * @param {SomeType} aName Some things to escape: and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] // Message: You have unescaped HTML characters < or & in a tag /** * @param {SomeType} aName Some things to escape: and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] // Message: You have unescaped Markdown backtick sequences in a tag /** * @param {SomeType} aName Some things to escape: * and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] // Message: You have unescaped HTML characters < or & in a tag /** * @param {SomeType} aName Some things to escape: * and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] // Message: You have unescaped Markdown backtick sequences in a tag ```` ## Passing examples The following patterns are not considered problems: ````ts /** * Some things to escape: <a> and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] /** * Some things to escape: and > and \`test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] /** * Some things to escape: < and & */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] /** * Some things to escape: ` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] /** * @param {SomeType} aName Some things to escape: <a> and > and `test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] /** * @param {SomeType} aName Some things to escape: and > and \`test` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] /** * @param {SomeType} aName Some things to escape: < and & */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] /** * @param {SomeType} aName Some things to escape: ` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] /** * Nothing * to escape */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] /** * @example * ``` * Some things to escape: and > and ઼ and `test` * ``` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeHTML":true}] /** * @example * ``` * Some things to escape: and > and ઼ and `test` * ``` */ // "jsdoc/text-escaping": ["error"|"warn", {"escapeMarkdown":true}] ```` --- # ts-method-signature-style Inspired by `typescript-eslint`'s [method-signature-style](https://typescript-eslint.io/rules/method-signature-style/) rule. See that rule for the rationale behind preferring the function property. ## Options The first option is a string with the following possible values: "method", "property". The next option is an object with the following properties. ### enableFixer Whether to enable the fixer. Defaults to `true`. ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|false| |Settings|| |Options|string ("method", "property") followed by object with `enableFixer`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {{ * func(arg: string): number * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "property"] // Message: Found method signature; prefer function property. /** * @param {{ * func(arg: string): number * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "property",{"enableFixer":false}] // Message: Found method signature; prefer function property. /** * @param {{ * func(arg: number): void * func(arg: string): void * func(arg: boolean): void * }} someName */ // Message: Found method signature; prefer function property. /** * @param {{ * func: (arg: string) => number * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method"] // Message: Found function property; prefer method signature. /** * @param {{ * func: (arg: string) => number * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method",{"enableFixer":false}] // Message: Found function property; prefer method signature. /** * @type {{ * func: ((arg: number) => void) & * ((arg: string) => void) & * ((arg: boolean) => void) * }} */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method"] // Message: Found function property; prefer method signature. /** * @param {{ * func: ((arg: number) => void) & * ((arg: string) => void) & * ((arg: boolean) => void) * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method",{"enableFixer":false}] // Message: Found function property; prefer method signature. /** * @param {{ * "func"(arg: string): number * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "property"] // Message: Found method signature; prefer function property. /** * @param {{ * 'func': (arg: string) => number * }} someName */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method"] // Message: Found function property; prefer method signature. /** @type {{ * func: ((arg: number) => void) & * ((arg: string) => void) & * ((arg: boolean) => void) * }} */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method"] // Message: Found function property; prefer method signature. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {{ * func: (arg: string) => number * }} */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "property"] /** * @param {{ * func: ((arg: number) => void) & * ((arg: string) => void) & * ((arg: boolean) => void) * }} */ /** * @param {abc<} */ /** * @param {{ * func: ((arg: number) => void) & (SomeType) * }} */ // "jsdoc/ts-method-signature-style": ["error"|"warn", "method"] ```` --- # ts-no-empty-object-type Warns against use of the empty object type which, in TypeScript, means "any value that is defined". ## Options ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|true| |Settings|| |Options|| ## Failing examples The following patterns are considered problems: ````ts /** * @param {{}} someName */ // Message: No empty object type. /** * @param {(string|{})} someName */ // Message: No empty object type. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {{a: string}} someName */ /** * @param {({a: string} & {b: number})} someName */ /** * @param {BadType<} someName */ /** * @param {{}} someName */ // Settings: {"jsdoc":{"mode":"jsdoc"}} ```` --- # ts-no-unnecessary-template-expression Catches unnecessary template expressions such as string expressions within a template literal. ## Options A single options object has the following properties. ### enableFixer Whether to enable the fixer. Defaults to `true`. ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|false| |Settings|| |Options|`enableFixer`| ## Failing examples The following patterns are considered problems: ````ts /** * @type {`A${'B'}`} */ // Message: Found an unnecessary string literal within a template. /** * @type {`A${'B'}`} */ // "jsdoc/ts-no-unnecessary-template-expression": ["error"|"warn", {"enableFixer":false}] // Message: Found an unnecessary string literal within a template. /** * @type {(`A${'B'}`)} */ // Message: Found an unnecessary string literal within a template. /** * @type {`A${'B'}`|SomeType} */ // Message: Found an unnecessary string literal within a template. /** * @type {`${B}`} */ // Message: Found a lone template expression within a template. /** * @type {`${B}`} */ // "jsdoc/ts-no-unnecessary-template-expression": ["error"|"warn", {"enableFixer":false}] // Message: Found a lone template expression within a template. /** * @type {`A${'B'}${'C'}`} */ // Message: Found an unnecessary string literal within a template. /** * @type {`A${'B'}C`} */ // Message: Found an unnecessary string literal within a template. /** * @type {`${'B'}`} */ // Message: Found an unnecessary string literal within a template. /** * @type {(`${B}`)} */ // Message: Found a lone template expression within a template. /** * @type {`${B}` | number} */ // Message: Found a lone template expression within a template. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @type {`AB`} */ /** * @type {`A${C}B`} */ /** * @param {BadType<} someName */ /** * @param {`A${'B'}`} someName */ // Settings: {"jsdoc":{"mode":"jsdoc"}} ```` --- # ts-prefer-function-type Inspired by `typescript-eslint`'s [prefer-function-type](https://typescript-eslint.io/rules/prefer-function-type/) rule. Chooses the more succinct function property over a call signature if there are no other properties on the signature. ## Options A single options object has the following properties. ### enableFixer Whether to enable the fixer or not ||| |---|---| |Context|everywhere| |Tags|``| |Recommended|false| |Settings|| |Options|`enableFixer`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {{ * (arg: string): void; * }} someName */ // Message: Call signature found; function type preferred. /** * @param {{ * (arg: string): void; * }} someName */ // "jsdoc/ts-prefer-function-type": ["error"|"warn", {"enableFixer":false}] // Message: Call signature found; function type preferred. /** * @param {(string | { * (arg: string): void; * })} someName */ // Message: Call signature found; function type preferred. ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {() => number} someName */ /** * @param {{ * (arg: string): void; * abc: number; * }} someName */ /** * @param {{ * (data: string): number; * (id: number): string; * }} someName */ /** * @param {BadType<} someName */ ```` --- # type-formatting Formats JSDoc type values. Note that this rule should be considered **experimental**. The stringification might not preserve other aspects of your original formatting and there could be errors. Currently offers the following options for formatting types. ## Options A single options object has the following properties. ### arrayBrackets Determines how array generics are represented. Set to `angle` for the style `Array` or `square` for the style `type[]`. Defaults to "square". ### arrowFunctionPostReturnMarkerSpacing The space character (if any) to use after return markers (`=>`). Defaults to " ". ### arrowFunctionPreReturnMarkerSpacing The space character (if any) to use before return markers (`=>`). Defaults to " ". ### enableFixer Whether to enable the fixer. Defaults to `true`. ### functionOrClassParameterSpacing The space character (if any) to use between function or class parameters. Defaults to " ". ### functionOrClassPostGenericSpacing The space character (if any) to use after a generic expression in a function or class. Defaults to "". ### functionOrClassPostReturnMarkerSpacing The space character (if any) to use after return markers (`:`). Defaults to "". ### functionOrClassPreReturnMarkerSpacing The space character (if any) to use before return markers (`:`). Defaults to "". ### functionOrClassTypeParameterSpacing The space character (if any) to use between type parameters in a function or class. Defaults to " ". ### genericAndTupleElementSpacing The space character (if any) to use between elements in generics and tuples. Defaults to " ". ### genericDot Boolean value of whether to use a dot before the angled brackets of a generic (e.g., `SomeType.`). Defaults to `false`. ### keyValuePostColonSpacing The amount of spacing (if any) after the colon of a key-value or object-field pair. Defaults to " ". ### keyValuePostKeySpacing The amount of spacing (if any) immediately after keys in a key-value or object-field pair. Defaults to "". ### keyValuePostOptionalSpacing The amount of spacing (if any) after the optional operator (`?`) in a key-value or object-field pair. Defaults to "". ### keyValuePostVariadicSpacing The amount of spacing (if any) after a variadic operator (`...`) in a key-value pair. Defaults to "". ### methodQuotes The style of quotation mark for surrounding method names when quoted. Defaults to `double` ### objectFieldIndent A string indicating the whitespace to be added on each line preceding an object property-value field. Defaults to the empty string. ### objectFieldQuote Whether and how object field properties should be quoted (e.g., `{"a": string}`). Set to `single`, `double`, or `null`. Defaults to `null` (no quotes unless required due to special characters within the field). Digits will be kept as is, regardless of setting (they can either represent a digit or a string digit). ### objectFieldSeparator For object properties, specify whether a "semicolon", "comma", "linebreak", "semicolon-and-linebreak", or "comma-and-linebreak" should be used after each object property-value pair. Defaults to `"comma"`. ### objectFieldSeparatorOptionalLinebreak Whether `objectFieldSeparator` set to `"semicolon-and-linebreak"` or `"comma-and-linebreak"` should be allowed to optionally drop the linebreak. Defaults to `true`. ### objectFieldSeparatorTrailingPunctuation If `separatorForSingleObjectField` is not in effect (i.e., if it is `false` or there are multiple property-value object fields present), this property will determine whether to add punctuation corresponding to the `objectFieldSeparator` (e.g., a semicolon) to the final object field. Defaults to `false`. ### parameterDefaultValueSpacing The space character (if any) to use between the equal signs of a default value. Defaults to " ". ### postMethodNameSpacing The space character (if any) to add after a method name. Defaults to "". ### postNewSpacing The space character (if any) to add after "new" in a constructor. Defaults to " ". ### separatorForSingleObjectField Whether to apply the `objectFieldSeparator` (e.g., a semicolon) when there is only one property-value object field present. Defaults to `false`. ### stringQuotes How string literals should be quoted (e.g., `"abc"`). Set to `single` or `double`. Defaults to 'double'. ### typeBracketSpacing A string of spaces that will be added immediately after the type's initial curly bracket and immediately before its ending curly bracket. Defaults to the empty string. ### unionSpacing Determines the spacing to add to unions (`|`). Defaults to a single space (`" "`). ||| |---|---| |Context|everywhere| |Tags|`param`, `property`, `returns`, `this`, `throws`, `type`, `typedef`, `yields`| |Recommended|false| |Settings|`mode`| |Options|`arrayBrackets`, `arrowFunctionPostReturnMarkerSpacing`, `arrowFunctionPreReturnMarkerSpacing`, `enableFixer`, `functionOrClassParameterSpacing`, `functionOrClassPostGenericSpacing`, `functionOrClassPostReturnMarkerSpacing`, `functionOrClassPreReturnMarkerSpacing`, `functionOrClassTypeParameterSpacing`, `genericAndTupleElementSpacing`, `genericDot`, `keyValuePostColonSpacing`, `keyValuePostKeySpacing`, `keyValuePostOptionalSpacing`, `keyValuePostVariadicSpacing`, `methodQuotes`, `objectFieldIndent`, `objectFieldQuote`, `objectFieldSeparator`, `objectFieldSeparatorOptionalLinebreak`, `objectFieldSeparatorTrailingPunctuation`, `parameterDefaultValueSpacing`, `postMethodNameSpacing`, `postNewSpacing`, `separatorForSingleObjectField`, `stringQuotes`, `typeBracketSpacing`, `unionSpacing`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {{a: string; b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldSeparator":"semicolon"}] // Message: Inconsistent semicolon separator usage /** * @param {{a: string; b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldSeparator":"semicolon","objectFieldSeparatorTrailingPunctuation":true}] // Message: Inconsistent semicolon separator usage /** * @param {{a: string; b: number; c: boolean,}} cfg */ // Settings: {"jsdoc":{"mode":"permissive"}} // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldSeparator":"semicolon"}] // Message: Inconsistent semicolon separator usage /** * @param {{a: string; b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"enableFixer":false,"objectFieldSeparator":"semicolon"}] // Message: Inconsistent semicolon separator usage /** * @param {{a: string, b: number; c: boolean;}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldSeparator":"comma"}] // Message: Inconsistent comma separator usage /** * @param {{a: string, b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"linebreak"}] // Message: Inconsistent linebreak separator usage /** * @param {{ * a: string, * b: number; * c: boolean, * }} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"linebreak"}] // Message: Inconsistent linebreak separator usage /** * @param {'abc'} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"stringQuotes":"double"}] // Message: Inconsistent double string quotes usage /** * @param {Array} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"arrayBrackets":"square"}] // Message: Array bracket style should be square /** * @param {SomeType} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericDot":true}] // Message: Dot usage should be true /** * @param {{a: string}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldQuote":"double"}] // Message: Inconsistent object field quotes double /** * @param {{"a": string}} cfg */ // Message: Inconsistent object field quotes null /** * @param {{a: string}} cfg A long * description */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon","separatorForSingleObjectField":true}] // Message: Inconsistent semicolon separator usage /** @param {{a: string, b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"linebreak"}] // Message: Inconsistent linebreak separator usage /** * @param {{a: string, b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"linebreak"}] // Message: Inconsistent linebreak separator usage /** @param {{a: string, b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"linebreak"}] // Message: Inconsistent linebreak separator usage /** * @param {{ * a: string, * b: number * }} cfg A long * description */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon-and-linebreak"}] // Message: Inconsistent semicolon-and-linebreak separator usage /** * @param {{ * a: string, * b: number * }} cfg A long * description */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon-and-linebreak","objectFieldSeparatorTrailingPunctuation":true}] // Message: Inconsistent semicolon-and-linebreak separator usage /** * @param {ab | cd} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"unionSpacing":""}] // Message: Inconsistent "" union spacing usage /** * Due to jsdoc-type-pratt-parser not consuming whitespace, the exact * error will not be reported. * @param {ab|cd} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"unionSpacing":" "}] // Message: There was an error with type formatting /** * Due to jsdoc-type-pratt-parser representing the separator at the * object level, the exact error will not be reported. * @param {{a: string, b: number; c: boolean,}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldSeparator":"comma"}] // Message: There was an error with type formatting /** * @type {string} */ // "jsdoc/type-formatting": ["error"|"warn", {"typeBracketSpacing":" "}] // Message: Must have initial and final " " spacing /** * @type { string } */ // "jsdoc/type-formatting": ["error"|"warn", {"typeBracketSpacing":""}] // Message: Must have no initial spacing /** * @param {{a: string, b: number}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon-and-linebreak","objectFieldSeparatorOptionalLinebreak":true}] // Message: Inconsistent semicolon-and-linebreak separator usage /** * @param {{ * a: string, * b: number * }} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon-and-linebreak","objectFieldSeparatorOptionalLinebreak":true}] // Message: Inconsistent semicolon-and-linebreak separator usage /** * @param {SomeType} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericAndTupleElementSpacing":""}] // Message: Element spacing should be "" /** * @param {[string, number]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericAndTupleElementSpacing":""}] // Message: Element spacing should be "" /** * @param {(x: T) => U} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"parameterDefaultValueSpacing":""}] // Message: Default value spacing should be "" /** * @param {{a: 3}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostColonSpacing":""}] // Message: Post colon spacing should be "" /** * @param {{a: 3}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostKeySpacing":" "}] // Message: Post key spacing should be " " /** * @param {{a?: 3}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostOptionalSpacing":" "}] // Message: Post optional (`?`) spacing should be " " /** * @param {[a: 3]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostColonSpacing":""}] // Message: Post colon spacing should be "" /** * @param {[a: 3]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostKeySpacing":" "}] // Message: Post key spacing should be " " /** * @param {[a?: 3]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostOptionalSpacing":" "}] // Message: Post optional (`?`) spacing should be " " /** * @param {() => void} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"arrowFunctionPostReturnMarkerSpacing":""}] // Message: Post-return-marker spacing should be "" /** * @param {() => void} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"arrowFunctionPreReturnMarkerSpacing":""}] // Message: Pre-return-marker spacing should be "" /** * @param {{hello(): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"postMethodNameSpacing":" "}] // Message: Post-method-name spacing should be " " /** * @param {{new (): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"postNewSpacing":""}] // Message: Post-`new` spacing should be "" /** * @param {function(): void} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassPreReturnMarkerSpacing":" "}] // Message: Pre-return-marker spacing should be " " /** * @param {{new (): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassPostReturnMarkerSpacing":""}] // Message: Post-return-marker spacing should be "" /** * @param {{method(a: string, b: number): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassParameterSpacing":""}] // Message: Parameter spacing should be "" /** * @param {{method(a: T, b: number): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassPostGenericSpacing":" "}] // Message: Post-generic spacing should be " " /** * @param {{method(a: T, b: U): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassTypeParameterSpacing":""}] // Message: Type parameter spacing should be "" /** * @param {{'some-method'(a: string, b: number): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"methodQuotes":"double"}] // Message: Method quoting style should be "double" /** * @param {[a: string, ...b: number]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostVariadicSpacing":" "}] // Message: Post variadic (`...`) spacing should be " " ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {{a: string; b: number; c: boolean}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldSeparator":"semicolon"}] /** * @param {"abc"} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"stringQuotes":"double"}] /** * @param {string[]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"arrayBrackets":"square"}] /** * @param {SomeType.} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericDot":true}] /** * @param {A<} badParam */ /** * @param {{"a bc": string}} quotedKeyParam */ /** * @param {{55: string}} quotedKeyParam */ /** * @param {{"a-b-c": string}} quotedKeyParam */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldQuote":null}] /** * @param {{55: string}} quotedKeyParam */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldQuote":"double"}] /** * @param {ab | cd} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"unionSpacing":" "}] /** * @param {ab|cd} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"unionSpacing":""}] /** * @param cfg */ /** * @param {{a: string; b: number}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon-and-linebreak","objectFieldSeparatorOptionalLinebreak":true}] /** * @param {{ * a: string; * b: number * }} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"objectFieldIndent":" ","objectFieldSeparator":"semicolon-and-linebreak","objectFieldSeparatorOptionalLinebreak":true}] /** * @param {SomeType} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericAndTupleElementSpacing":""}] /** * @param {SomeType} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericAndTupleElementSpacing":" "}] /** * @param {[string,number]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"genericAndTupleElementSpacing":""}] /** * @param {(x: T) => U} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"parameterDefaultValueSpacing":""}] /** * @param {{a:3}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostColonSpacing":""}] /** * @param {{a : 3}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostKeySpacing":" "}] /** * @param {{a? : 3}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostOptionalSpacing":" "}] /** * @param {[a:3]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostColonSpacing":""}] /** * @param {[a : 3]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostKeySpacing":" "}] /** * @param {[a? : 3]} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"keyValuePostOptionalSpacing":" "}] /** * @param {() =>void} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"arrowFunctionPostReturnMarkerSpacing":""}] /** * @param {()=> void} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"arrowFunctionPreReturnMarkerSpacing":""}] /** * @param {{hello (): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"postMethodNameSpacing":" "}] /** * @param {{new(): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"postNewSpacing":""}] /** * @param {{new (): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"postNewSpacing":" "}] /** * @param {function() : void} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassPreReturnMarkerSpacing":" "}] /** * @param {{new ():void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassPostReturnMarkerSpacing":""}] /** * @param {{method(a: string,b: number): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassParameterSpacing":""}] /** * @param {{method (a: T, b: number): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassPostGenericSpacing":" "}] /** * @param {{method(a: T, b: U): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"functionOrClassTypeParameterSpacing":""}] /** * @param {{"some-method"(a: string, b: number): void}} cfg */ // "jsdoc/type-formatting": ["error"|"warn", {"methodQuotes":"double"}] ```` --- # valid-types * [Options](#user-content-valid-types-options) * [`allowEmptyNamepaths`](#user-content-valid-types-options-allowemptynamepaths) * [Context and settings](#user-content-valid-types-context-and-settings) * [Failing examples](#user-content-valid-types-failing-examples) * [Passing examples](#user-content-valid-types-passing-examples) Requires all types/namepaths to be valid JSDoc, Closure compiler, or TypeScript types (configured by `settings.jsdoc.mode`). Note that what determines a valid type is handled by our type parsing engine, [jsdoc-type-pratt-parser](https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser), using [`settings.jsdoc.mode`](#user-content-eslint-plugin-jsdoc-settings-mode) to determine whether to use jsdoc-type-pratt-parser's "permissive" parsing or the stricter "jsdoc", "typescript", "closure" modes. The following tags have their "type" portions (the segment within brackets) checked (though those portions may sometimes be confined to namepaths, e.g., `@modifies`): 1. Tags with required types: `@type`, `@implements` 1. Tags with required types in Closure or TypeScript: `@this`, `@define` (Closure only) 1. Tags with optional types: `@enum`, `@member` (`@var`), `@typedef`, `@augments` (or `@extends`), `@class` (or `@constructor`), `@constant` (or `@const`), `@module` (module paths are not planned for TypeScript), `@namespace`, `@throws`, `@exception`, `@yields` (or `@yield`), `@modifies` (undocumented jsdoc); `@param` (`@arg`, `@argument`), `@property` (`@prop`), and `@returns` (`@return`) also fall into this category, but while this rule will check their type validity, we leave the requiring of the type portion to the rules `require-param-type`, `require-property-type`, and `require-returns-type`, respectively. 1. Tags with types that are available optionally in Closure: `@export`, `@package`, `@private`, `@protected`, `@public`, `@static`; `@template` (TypeScript also) 1. Tags with optional types that may take free text instead: `@throws` The following tags have their name/namepath portion (the non-whitespace text after the tag name) checked: 1. Name(path)-defining tags requiring namepath: `@event`, `@callback`, `@exports` (JSDoc only), `@external`, `@host`, `@name`, `@typedef` (JSDoc only), and `@template` (TypeScript/Closure only); `@param` (`@arg`, `@argument`) and `@property` (`@prop`) also fall into this category, but while this rule will check their namepath validity, we leave the requiring of the name portion to the rules `require-param-name` and `require-property-name`, respectively. 1. Name(path)-defining tags (which may have value without namepath or their namepath can be expressed elsewhere on the block): `@class`, `@constructor`, `@constant`, `@const`, `@function`, `@func`, `@method`, `@interface` (non-Closure only), `@member`, `@var`, `@mixin`, `@namespace`, `@module` (module paths are not planned for TypeScript) 1. Name(path)-pointing tags requiring namepath: `@alias`, `@augments`, `@extends` (JSDoc only), `@lends`, `@memberof`, `@memberof!`, `@mixes`, `@requires`, `@this` (JSDoc only) 1. Name(path)-pointing tags (which may have value without namepath or their namepath can be expressed elsewhere on the block): `@listens`, `@fires`, `@emits`. 1. Name(path)-pointing tags which may have free text or a namepath: `@see` 1. Name(path)-pointing tags (multiple names in one): `@borrows` ...with the following applying to the above sets: - Expect tags in set 1-4 to have a valid namepath if present - Prevent sets 2 and 4 from being empty by setting `allowEmptyNamepaths` to `false` as these tags might have some indicative value without a path or may allow a name expressed elsewhere on the block (but sets 1 and 3 will always fail if empty) - For the special case of set 6, i.e., `@borrows as `, check that both namepaths are present and valid and ensure there is an `as ` between them. In the case of ``, it can be preceded by one of the name path operators, `#`, `.`, or `~`. - For the special case of `@memberof` and `@memberof!` (part of set 3), as per the [specification](https://jsdoc.app/tags-memberof.html), they also allow `#`, `.`, or `~` at the end (which is not allowed at the end of normal paths). If you define your own tags, `settings.jsdoc.structuredTags` will allow these custom tags to be checked, with the name portion of tags checked for valid namepaths (based on the tag's `name` value), their type portions checked for valid types (based on the tag's `type` value), and either portion checked for presence (based on `false` `name` or `type` values or their `required` value). See the setting for more details. ## Options A single options object has the following properties. ### allowEmptyNamepaths Set to `false` to bulk disallow empty name paths with namepath groups 2 and 4 (these might often be expected to have an accompanying name path, though they have some indicative value without one; these may also allow names to be defined in another manner elsewhere in the block); you can use `settings.jsdoc.structuredTags` with the `required` key set to "name" if you wish to require name paths on a tag-by-tag basis. Defaults to `true`. ## Context and settings ||| |---|---| |Context|everywhere| |Tags|For name only unless otherwise stated: `alias`, `augments`, `borrows`, `callback`, `class` (for name and type), `constant` (for name and type), `enum` (for type), `event`, `external`, `fires`, `function`, `implements` (for type), `interface`, `lends`, `listens`, `member` (for name and type), `memberof`, `memberof!`, `mixes`, `mixin`, `modifies`, `module` (for name and type), `name`, `namespace` (for name and type), `param` (for name and type), `property` (for name and type), `returns` (for type), `see` (optionally for name), `this`, `throws` (for type), `type` (for type), `typedef` (for name and type), `yields` (for type)| |Aliases|`extends`, `constructor`, `const`, `host`, `emits`, `func`, `method`, `var`, `arg`, `argument`, `prop`, `return`, `exception`, `yield`| |Closure-only|For type only: `package`, `private`, `protected`, `public`, `static`| |Recommended|true| |Options|`allowEmptyNamepaths`| |Settings|`mode`, `structuredTags`| ## Failing examples The following patterns are considered problems: ````ts /** * @param {Array): !Array} */ parseArray = function(parser) { return function(array) { return array.map(parser); }; }; // Settings: {"jsdoc":{"mode":"closure"}} // Message: Syntax error in namepath: T<~ /** * @template T, R<~ * @param {function(!T): !R} parser * @return {function(!Array): !Array} */ parseArray = function(parser) { return function(array) { return array.map(parser); }; }; // Settings: {"jsdoc":{"mode":"closure"}} // Message: Syntax error in namepath: R<~ /** * @template T, R<~ * @param {function(!T): !R} parser * @return {function(!Array): !Array} */ parseArray = function(parser) { return function(array) { return array.map(parser); }; }; // Settings: {"jsdoc":{"mode":"closure"}} // Message: Syntax error in namepath: R<~ /** * @suppress */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: Tag @suppress must have a type in "closure" mode. /** * @suppress {visibility} sth */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: @suppress should not have a name in "closure" mode. /** * @suppress {visibility|blah} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // Message: Syntax error in suppress type: blah /** * @param {Object[]} employees * @param {string} employees[.name - The name of an employee. */ function quux () {} // Message: Invalid name: unpaired brackets /** * @param {Object[]} employees * @param {string} [] - The name of an employee. */ function quux () {} // Message: Invalid name: empty name /** * @param {string} [name=] - The name of an employee. */ function quux () {} // Message: Invalid name: empty default value /** * @param {string} [name==] - The name of an employee. */ function quux () {} // Message: Invalid name: invalid default value syntax /** * @type {{message: string?}} */ function quux (items) { } // Settings: {"jsdoc":{"mode":"closure"}} // Message: Syntax error in type: JsdocTypeNullable /** * @type {[message: string?]} */ function quux (items) { } // Settings: {"jsdoc":{"mode":"typescript"}} // Message: Syntax error in type: JsdocTypeNullable /** * An inline {@link} tag without content. */ // Message: Inline tag "link" missing content /** * An inline {@tutorial} tag without content. */ // Message: Inline tag "tutorial" missing content /** * @param {SomeType} aName An inline {@link} tag without content. */ // Message: Inline tag "link" missing content /** * With reserved word in type * @param {Array} foo */ function quux() { } // Message: Syntax error in type: Array ```` ## Passing examples The following patterns are not considered problems: ````ts /** * @param {Array} foo */ function quux() { } /** * @param {string} foo */ function quux() { } /** * @param foo */ function quux() { } /** * @borrows foo as bar */ function quux() { } /** * @borrows foo as #bar */ function quux() { } /** * @see foo% */ function quux() { } /** * @alias module:namespace.SomeClass#event:ext_anevent */ function quux() { } /** * @callback foo */ function quux() { } /** * @callback */ function quux() { } // "jsdoc/valid-types": ["error"|"warn", {"allowEmptyNamepaths":true}] /** * @class */ function quux() { } /** * @see {@link foo} */ function quux() { } // Settings: {"jsdoc":{"structuredTags":{"see":{"name":"namepath-referencing","required":["name"]}}}} /** * * @fires module:namespace.SomeClass#event:ext_anevent */ function quux() { } /** * @memberof module:namespace.SomeClass~ */ function quux() { } /** * @memberof! module:namespace.SomeClass. */ function quux() { } /** * */ function quux() { } /** * @aCustomTag */ function quux() { } /** * @constant {string} */ const FOO = 'foo'; /** * @constant {string} FOO */ const FOO = 'foo'; /** * @extends Foo */ class Bar {}; /** * @extends Foo */ class Bar {}; /** * @extends {Foo} */ class Bar {}; // Settings: {"jsdoc":{"mode":"closure"}} /** * @typedef {number | string} UserDefinedType */ /** * @typedef {number | string} */ let UserDefinedGCCType; // Settings: {"jsdoc":{"mode":"closure"}} /** * @modifies {foo | bar} */ function quux (foo, bar, baz) {} /** * @this {Navigator} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @export {SomeType} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @define {boolean} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @define */ function quux () {} /** * Foo function. * * @interface foo */ function foo(bar) {} // Settings: {"jsdoc":{"mode":"typescript"}} /** * Foo function. * * @param {[number, string]} bar - The bar array. */ function foo(bar) {} // Settings: {"jsdoc":{"mode":"typescript"}} /** * Foo function. * * @param {[number, string]} bar - The bar array. */ function foo(bar) {} /** * Foo function. * * @param {[number, string]} bar - The bar array. */ function foo(bar) {} // Settings: {"jsdoc":{"mode":"permissive"}} /** * @typedef {SomeType} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} // "jsdoc/valid-types": ["error"|"warn", {"allowEmptyNamepaths":false}] /** * @private {SomeType} */ function quux () {} // Settings: {"jsdoc":{"mode":"closure"}} /** * @param */ function quux() { } // "jsdoc/valid-types": ["error"|"warn", {"allowEmptyNamepaths":false}] /** * @see */ function quux() { } // Settings: {"jsdoc":{"structuredTags":{"see":{"name":"namepath-referencing"}}}} /** * @template T, R * @param {function(!T): !R} parser * @return {function(!Array): !Array} */ parseArray = function(parser) { return function(array) { return array.map(parser); }; }; // Settings: {"jsdoc":{"mode":"closure"}} /** * @template T, R<~ * @param {function(!T): !R} parser * @return {function(!Array): !Array} */ parseArray = function(parser) { return function(array) { return array.map(parser); }; }; // Settings: {"jsdoc":{"mode":"jsdoc"}} /** * @template {string} K - K must be a string or string literal * @template {{ serious: string }} Seriousalizable - must have a serious property * @param {K} key * @param {Seriousalizable} object */ function seriousalize(key, object) { // ???? } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @module foo/bar */ /** * @module module:foo/bar */ /** * @template invalid namepath,T Description */ function f() {} // Settings: {"jsdoc":{"mode":"closure"}} /** * Description of complicated type. * * @template T Description of the T type parameter. * @template U - Like other tags, this can have an optional hyphen before the description. * @template V,W More parameters * @template W,X - Also with a hyphen */ type ComplicatedType = never /** Multi-line typedef for an options object type. * * @typedef {{ * prop: number * }} MyOptions */ /** * @extends {SomeType} */ class quux {} // Settings: {"jsdoc":{"mode":"typescript"}} /** * @suppress {visibility|underscore} */ function quux() { } // Settings: {"jsdoc":{"mode":"closure"}} /** * @param {string} id * @param {Object} options * @param {boolean} options.isSet * @param {string} options.module */ function quux ( id, options ) { } /** * Assign the project to a list of employees. * @param {Object[]} employees - The employees who are responsible for the project. * @param {string} employees[].name - The name of an employee. * @param {string} employees[].department - The employee's department. */ function assign(employees) { // ... } // "jsdoc/valid-types": ["error"|"warn", {"allowEmptyNamepaths":true}] /** * @param {typeof obj["level1"]["level2"]} foo * @param {Parameters[0]} ghi * @param {{[key: string]: string}} hjk */ function quux() { } // Settings: {"jsdoc":{"mode":"typescript"}} /** * @returns {Promise<{publicKey, privateKey}>} - The public and private key */ /** * Some other {@inline} tag. */ /** * @param {SomeType} aName An inline {@link text} tag with content. */ /** * An inline {@link text} tag with content. */ /** * @param typeof * @param readonly * @param import * @param is */ function quux() { } /** * @import { TestOne, TestTwo } from "./types" */ /** * @returns {@link SomeType} */ /** * @template {string} Selector * @template {keyof GlobalEventHandlersEventMap} TEventType * @template {Element} [TElement=import('typed-query-selector/parser').ParseSelector] * @param {Selector} selector * @param {TEventType} type * @param {import('delegate-it').DelegateEventHandler} callback * @param {Omit} [options] * @returns {void} */ export function onGlobalEvent (selector, type, callback, options) { delegate(document, selector, type, callback, options) } /** * Even if added to `structuredTags` as in our recommended config, * we don't want `valid-types` to report since * `jsdoc/require-next-type` already does this. * @next */ function a () {} // Settings: {"jsdoc":{"structuredTags":{"next":{"required":["type"]}}}} /** * With reserved word in name * @typedef {SomeType} import */ /** * With reserved word in namepath * @param {SomeType} import */ /** * @param readonly */ /** * @param {boolean} readonly */ /** * @param {object} params * @param {boolean} params.readonly */ /** * An object interface * @typedef {Object} FooBar * @property {boolean} readonly * @property {boolean} private * @property {boolean} public * @property {boolean} constant */ /** * @param {object} props * @param {string} props.is */ class Test { /** * @returns {this} */ method() { return this; } } /** * @typedef {Object} module:src/core/Player~mediaFormat */ // Settings: {"jsdoc":{"mode":"jsdoc"}} let SettingName = /** @type {const} */ ({ THEME: `theme`, }) ```` --- ## Settings * [Allow tags (`@private` or `@internal`) to disable rules for that comment block](#user-content-settings-allow-tags-private-or-internal-to-disable-rules-for-that-comment-block) * [`maxLines` and `minLines`](#user-content-settings-maxlines-and-minlines) * [Mode](#user-content-settings-mode) * [Alias Preference](#user-content-settings-alias-preference) * [Default Preferred Aliases](#user-content-settings-alias-preference-default-preferred-aliases) * [`@override`/`@augments`/`@extends`/`@implements`/`@ignore` Without Accompanying `@param`/`@description`/`@example`/`@returns`/`@throws`/`@yields`](#user-content-settings-override-augments-extends-implements-ignore-without-accompanying-param-description-example-returns-throws-yields) * [Settings to Configure `check-types` and `no-undefined-types`](#user-content-settings-settings-to-configure-check-types-and-no-undefined-types) * [`structuredTags`](#user-content-settings-structuredtags) * [`contexts`](#user-content-settings-contexts) ### Allow tags (@private or @internal) to disable rules for that comment block - `settings.jsdoc.ignorePrivate` - Disables all rules for the comment block on which a `@private` tag (or `@access private`) occurs. Defaults to `false`. Note: This has no effect with the rule `check-access` (whose purpose is to check access modifiers) or `empty-tags` (which checks `@private` itself). - `settings.jsdoc.ignoreInternal` - Disables all rules for the comment block on which a `@internal` tag occurs. Defaults to `false`. Note: This has no effect with the rule `empty-tags` (which checks `@internal` itself). ### maxLines and minLines One can use `minLines` and `maxLines` to indicate how many line breaks (if any) will be checked to find a JSDoc comment block before the given code block. These settings default to `0` and `1` respectively. In conjunction with the `require-jsdoc` rule, these settings can be enforced so as to report problems if a JSDoc block is not found within the specified boundaries. The settings are also used in the fixer to determine how many line breaks to add when a block is missing. ### Mode - `settings.jsdoc.mode` - Set to `typescript`, `closure`, or `jsdoc` (the default is now `typescript`). Note that if you do not wish to use separate `.eslintrc.*` files for a project containing both JavaScript and TypeScript, you can also use [`overrides`](https://eslint.org/docs/user-guide/configuring). You may also set to `"permissive"` to try to be as accommodating to any of the styles, but this is not recommended. Currently is used for the following: - `check-tag-names`: Determine valid tags and aliases - `no-undefined-types`: Only check `@template` for types in "closure" and "typescript" modes - `check-syntax`: determines aspects that may be enforced - `valid-types`: in non-Closure mode, `@extends`, `@package` and access tags (e.g., `@private`) with a bracketed type are reported as are missing names with `@typedef` - For type/namepath-checking rules, determine which tags will be checked for types/namepaths (Closure allows types on some tags which the others do not, so these tags will additionally be checked in "closure" mode) - For type-checking rules, impacts parsing of types (through [jsdoc-type-pratt-parser](https://github.com/simonseyock/jsdoc-type-pratt-parser) dependency) - Check preferred tag names - Disallows namepath on `@interface` for "closure" mode in `valid-types` (and avoids checking in other rules) Note that if you are using TypeScript syntax (and not just the TypeScript flavor of JSDoc which `mode` set to "typescript" implies), you may wish to use the `recommended-typescript` or `recommended-typescript-error` config. This will add rules such as `jsdoc/no-types` to expect you have no types expressed in JSDoc (since these can be added in TypeScript). ### Alias Preference Use `settings.jsdoc.tagNamePreference` to configure a preferred alias name for a JSDoc tag. The format of the configuration is: `: `, e.g. ```json { "rules": {}, "settings": { "jsdoc": { "tagNamePreference": { "param": "arg", "returns": "return" } } } } ``` Note: ESLint does not allow settings to have keys which conflict with `Object.prototype` e.g. `'constructor'`. To work around this, you can use the key `'tag constructor'`. One may also use an object with a `message` and `replacement`. The following will report the message `@extends is to be used over @augments as it is more evocative of classes than @augments` upon encountering `@augments`. ```json { "rules": {}, "settings": { "jsdoc": { "tagNamePreference": { "augments": { "message": "@extends is to be used over @augments as it is more evocative of classes than @augments", "replacement": "extends" } } } } } ``` If one wishes to reject a normally valid tag, e.g., `@todo`, one may set the tag to `false`: ```json { "rules": {}, "settings": { "jsdoc": { "tagNamePreference": { "todo": false } } } } ``` A project wishing to ensure no blocks are left excluded from entering the documentation, might wish to prevent the `@ignore` tag in the above manner. Or one may set the targeted tag to an object with a custom `message`, but without a `replacement` property: ```json { "rules": {}, "settings": { "jsdoc": { "tagNamePreference": { "todo": { "message": "We expect immediate perfection, so don't leave to-dos in your code." } } } } } ``` Note that the preferred tags indicated in the `settings.jsdoc.tagNamePreference` map will be assumed to be defined by `check-tag-names`. See `check-tag-names` for how that fact can be used to set an alias to itself to allow both the alias and the default (since aliases are otherwise not permitted unless used in `tagNamePreference`). #### Default Preferred Aliases The defaults in `eslint-plugin-jsdoc` (for tags which offer aliases) are as follows: - `@abstract` (over `@virtual`) - `@augments` (over `@extends`) - `@class` (over `@constructor`) - `@constant` (over `@const`) - `@default` (over `@defaultvalue`) - `@description` (over `@desc`) - `@external` (over `@host`) - `@file` (over `@fileoverview`, `@overview`) - `@fires` (over `@emits`) - `@function` (over `@func`, `@method`) - `@member` (over `@var`) - `@param` (over `@arg`, `@argument`) - `@property` (over `@prop`) - `@returns` (over `@return`) - `@throws` (over `@exception`) - `@yields` (over `@yield`) This setting is utilized by the the rule for tag name checking (`check-tag-names`) as well as in the `@param` and `@require` rules: - `check-param-names` - `check-tag-names` - `require-hyphen-before-param-description` - `require-description` - `require-param` - `require-param-description` - `require-param-name` - `require-param-type` - `require-returns` - `require-returns-check` - `require-returns-description` - `require-returns-type` ### @override/@augments/@extends/@implements/@ignore Without Accompanying @param/@description/@example/@returns/@throws/@yields The following settings allows the element(s) they reference to be omitted on the JSDoc comment block of the function or that of its parent class for any of the "require" rules (i.e., `require-param`, `require-description`, `require-example`, `require-returns`, `require-throws`, `require-yields`). * `settings.jsdoc.ignoreReplacesDocs` (`@ignore`) - Defaults to `true` * `settings.jsdoc.overrideReplacesDocs` (`@override`) - Defaults to `true` * `settings.jsdoc.augmentsExtendsReplacesDocs` (`@augments` or its alias `@extends`) - Defaults to `false`. * `settings.jsdoc.implementsReplacesDocs` (`@implements`) - Defaults to `false` The format of the configuration is as follows: ```json { "rules": {}, "settings": { "jsdoc": { "ignoreReplacesDocs": true, "overrideReplacesDocs": true, "augmentsExtendsReplacesDocs": true, "implementsReplacesDocs": true } } } ``` ### Settings to Configure check-types and no-undefined-types - `settings.jsdoc.preferredTypes` An option map to indicate preferred or forbidden types (if default types are indicated here, these will have precedence over the default recommendations for `check-types`). The keys of this map are the types to be replaced (or forbidden). These keys may include: 1. The "ANY" type, `*` 1. The pseudo-type `[]` which we use to denote the parent (array) types used in the syntax `string[]`, `number[]`, etc. 1. The pseudo-type `.<>` (or `.`) to represent the format `Array.` or `Object.` 1. The pseudo-type `<>` to represent the format `Array` or `Object` 1. A plain string type, e.g., `MyType` 1. A plain string type followed by one of the above pseudo-types (except for `[]` which is always assumed to be an `Array`), e.g., `Array.`, or `SpecialObject<>`. If a bare pseudo-type is used, it will match all parent types of that form. If a pseudo-type prefixed with a type name is used, it will only match parent types of that form and type name. The values can be: - `false` to forbid the type - a string to indicate the type that should be preferred in its place (and which `fix` mode can replace); this can be one of the formats of the keys described above. - Note that the format will not be changed unless you use a pseudo-type in the replacement. (For example, `'Array.<>': 'MyArray'` will change `Array.` to `MyArray.`, preserving the dot. To get rid of the dot, you must use the pseudo-type with `<>`, i.e., `'Array.<>': 'MyArray<>'`, which will change `Array.` to `MyArray`). - If you use a _bare_ pseudo-type in the replacement (e.g., `'MyArray.<>': '<>'`), the type will be converted to the format of the pseudo-type without changing the type name. For example, `MyArray.` will become `MyArray` but `Array.` will not be modified. - an object with: - the key `message` to provide a specific error message when encountering the discouraged type. - The message string will have the substrings with special meaning, `{{tagName}}` and `{{tagValue}}`, replaced with their corresponding value. - an optional key `replacement` with either of the following values: - a string type to be preferred in its place (and which `fix` mode can replace) - `false` (for forbidding the type) - an optional key `skipRootChecking` (for `check-types`) to allow for this type in the context of a root (i.e., a parent object of some child type) - an optional key `unifyParentAndChildTypeChecks` will treat `settings.jsdoc.preferredTypes` keys such as `SomeType` as matching not only child types such as an unadorned `SomeType` but also `SomeType` and `SomeType.` (and if the type is instead `Array` (or `[]`), it will match `aChildType[]`). If this setting is `false` or unset, the former format will only apply to types which are not parent types/unions whereas the latter formats will only apply for parent types/unions. The special types `[]`, `.<>` (or `.`), and `<>` act only as parent types (and will not match a bare child type such as `Array` even when unified, though, as mentioned, `Array` will match say `string[]` or `Array.` when unified). The special type `*` is only a child type. Note that there is no detection of parent and child type together, e.g., you cannot specify preferences for `string[]` specifically as distinct from say `number[]`, but you can target both with `[]` or the child types `number` or `string`. Note: the (deprecated) `jsdoc/check-types` option of the same name, if set to `true`, will override this behavior. Note that the preferred types indicated as targets in `settings.jsdoc.preferredTypes` map will be assumed to be defined by `no-undefined-types`. See the option of `check-types`, `unifyParentAndChildTypeChecks`, for how the keys of `preferredTypes` may have `<>` or `.<>` (or just `.`) appended and its bearing on whether types are checked as parents/children only (e.g., to match `Array` if the type is `Array` vs. `Array.`). Note that if a value is present both as a key and as a value, neither the key nor the value will be reported. Thus in `check-types`, this fact can be used to allow both `object` and `Object` if one has a `preferredTypes` key `object: 'Object'` and `Object: 'object'`. (In the default "typescript" mode, this object behavior is a default one.) Note that if there is an error [parsing](https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser) types for a tag with `check-types`, the function will silently ignore that tag, leaving it to the `valid-types` rule to report parsing errors. ### structuredTags An object indicating tags whose types and names/namepaths (whether defining or referencing namepaths) will be checked, subject to configuration. If the tags have predefined behavior or `allowEmptyNamepaths` behavior, this option will override that behavior for any specified tags, though this option can also be used for tags without predefined behavior. Its keys are tag names and its values are objects with the following optional properties: - `name` - String set to one of the following: - `"text"` - When a name is present, plain text will be allowed in the name position (non-whitespace immediately after the tag and whitespace), e.g., in `@throws This is an error`, "This" would normally be the name, but "text" allows non-name text here also. This is the default. - `"name-defining"` - Indicates the tag adds a name to definitions. May not be an arbitrary namepath, unlike `"namepath-defining"` - `"namepath-defining"` - As with `namepath-referencing`, but also indicates the tag adds a namepath to definitions, e.g., to prevent `no-undefined-types` from reporting references to that namepath. - `"namepath-referencing"` - This will cause any name position to be checked to ensure it is a valid namepath. You might use this to ensure that tags which normally allow free text, e.g., `@see` will instead require a namepath. - `"namepath-or-url-referencing"` - For inline tags which may point to a namepath or URL. - `false` - This will disallow any text in the name position. - `type`: - `true` - Allows valid types within brackets. This is the default. - `false` - Explicitly disallows any brackets or bracketed type. You might use this with `@throws` to suggest that only free form text is being input or with `@augments` (for "jsdoc" mode) to disallow Closure-style bracketed usage along with a required namepath. - (An array of strings) - A list of permissible types. - `required` - Array of one of the following (defaults to an empty array, meaning none are required): - One or both of the following strings (if both are included, then both are required): - `"name"` - Indicates that a name position is required (not just that if present, it is a valid namepath). You might use this with `see` to insist that a value (or namepath, depending on the `name` value) is always present. - `"type"` - Indicates that the type position (within curly brackets) is required (not just that if present, it is a valid type). You might use this with `@throws` or `@typedef` which might otherwise normally have their types optional. See the type groups 3-5 above. - `"typeOrNameRequired"` - Must have either type (e.g., `@throws {aType}`) or name (`@throws Some text`); does not require that both exist but disallows just an empty tag. ### contexts `settings.jsdoc.contexts` can be used as the default for any rules with a `contexts` property option. **Please note**: This will replace any default contexts, including for function rules, so if, for example, you exclude `FunctionDeclaration` here, rules like `require-param` will not check function declarations. See the "AST and Selectors" section for more on this format.