Shared: JSDoc
Summarizes JSDoc writing conventions. All typing is JSDoc — no TypeScript syntax, no .ts
files — so always annotate types with JSDoc.
The rules in this body apply to every JavaScript file, backend and frontend alike.
How the jsdoc-plugin rules actually in effect under this project's ESLint map to
each of this skill's conventions is summarized in
eslint-jsdoc-rules.md. If you write JSDoc as
this skill prescribes,
npm run lintproduces no jsdoc-related errors. Note that
lint also enforces such points as:
functiondeclarations and methods must have
JSDoc (empty constructors are not exempt), each
@paramrequires a type and a name,
and a function that returns a value needs
@returns(with a type). This skill goes
one step further and requires
@returnseven when nothing is returned ({void}).
Write object types with named parameters
- Do not use
{object}. - Write objects as an inline type literal, explicitly listing each property as a named parameter.
Example:
// NG
/**
* @param {object} params - Parameters.
* @param {string} params.alpha - Alpha.
*/
// OK
/**
* @param {{
* alpha: string
* }} params - Parameters.
*/
Name a single object argument `params`
- For a method that takes a single object argument, name the parameter
paramsunless there is a special reason not to.
// OK
/**
* @param {{
* alpha: string
* }} params - Parameters.
*/
Always write `@returns`
- Every function and method gets
@returns, even one that returns nothing. - For a function that returns nothing, write
@returns {void}(@returns {Promise<void>}
when it is async). Never omit the tag.
- Lint (
jsdoc/require-returns) only demands@returnswhen a value is actually returned,
so this skill is stricter than lint here (see
eslint-jsdoc-rules.md). The reason is that "returns
nothing" should be stated, not inferred from the absence of a tag.
// NG: returns nothing, so @returns is omitted
/**
* @param {{
* message: string
* }} params - Parameters.
*/
// OK
/**
* @param {{
* message: string
* }} params - Parameters.
* @returns {void}
*/
Attach a description to `@returns`
- Attach not just a type but also a description to
@returns. - The sole exception is
@returns {void}/@returns {Promise<void>}. There is no
returned value to describe, so the type stands on its own.
- Do not put a hyphen between the type and the description. The leading
-is a
@param convention (jsdoc/require-hyphen-before-param-description) and does not
apply to @returns.
- Lint (
jsdoc/require-returns-description) is off and does not force a description,
but this skill always attaches one for QA reasons (see
// NG: no description
/**
* @returns {string}
*/
// NG: a hyphen before the description
/**
* @returns {string} - Default characters to pick from.
*/
// OK
/**
* @returns {string} Default characters to pick from.
*/
Add `@public` to entry points
- Add
@publicto the JSDoc of any method that serves as an entry point accessed from outside.
/**
* Generate a random text of the given length.
*
* @param {{
* length: number
* }} params - Parameters.
* @returns {string | null} Generated random text, or null if it cannot be generated.
* @public
*/
generate ({
length,
}) {
// ...
}
Write array types as `Array<T>`
- Trailing-
[]array notation such asstring[]is prohibited. Always write it asArray<string>. - Reason: writing something like
{ alpha: number, beta: string }[]causes confusion for the reader.
// NG
/**
* @param {string[]} values - Values.
*/
// OK
/**
* @param {Array<string>} values - Values.
*/
Avoid vague types; write the most specific type you can
- Vague types such as
object/Object/any/*are not used unless clearly necessary. - Investigate the type and write it as a type literal with the most detailed properties possible,
or as a concrete type name.
- Make generics concrete as far as possible. Do not leave the element type vague as
Array<object>; write Array<UserEntity> instead.
// NG: vague element type and return type
/**
* @param {{
* users?: Array<object>
* }} params - Parameters.
* @returns {object} Users and their total count.
*/
// OK: investigate and write the detailed type
/**
* @param {{
* users?: Array<UserEntity>
* }} params - Parameters.
* @returns {{
* users: Array<UserEntity>
* total: number
* }} Users and their total count.
*/
`object` / `Object` is prohibited; use `Record<string, *>`
object/Objectis prohibited regardless of the reason.- Reason:
objectis dangerous in that it tolerates ambiguity includingnull. Even when you are
forced to represent an object with unknown keys, Record<string, *> is better.
- Still,
Record<string, *>is a last resort too; write a type literal with explicit properties
wherever possible.
// NG
/**
* @param {object} config - Config.
*/
// BETTER: when the keys are genuinely unknown
/**
* @param {Record<string, *>} config - Config.
*/
// BEST: when you can list the properties
/**
* @param {{
* host: string
* port: number
* }} config - Config.
*/
Do not write undefined type names (define custom types before referencing them)
- For type names written in JSDoc, anything other than built-in types (
string/number/
boolean / Array / * / null, etc.) and TS utility types (Record / Partial /
Pick / Omit / ReturnType, etc.) must be defined before it is referenced, via one of
@typedef / @class / @interface / import.
- Do not write undefined type names. Reason: they are a common source of typos and missing imports.
- For example, to write
Array<UserEntity>from the previous section, a@typedef(or the like) for
UserEntity must exist in the same file (or its import source).
// NG: UserEntity is not defined anywhere
/**
* @param {{
* users?: Array<UserEntity>
* }} params - Parameters.
*/
// OK: define it with @typedef before referencing it
/**
* @typedef {{
* id: number
* name: string
* }} UserEntity
*/
/**
* @param {{
* users?: Array<UserEntity>
* }} params - Parameters.
*/
The undefined-type-name check (
jsdoc/no-undefined-types) is off by default in
@openreachtech/eslint-config, so this skill enforces it rather than relying on lint.
Do not write `undefined` as a type (use `null`)
- Do not write
undefinedin a type, as in@returns {string | undefined}or@param {undefined}. - Express "no value" with
null, notundefined(e.g.@returns {string | null}). - For a function that returns nothing, write
@returns {void}, not@returns {undefined}
(see "Always write @returns" above).
- Exception: when a third-party module or the like requires
undefined, you may writeundefinedin
@returns and so on. If there is a way to avoid undefined, prefer that.
// NG
/**
* @returns {string | undefined} Generated text.
*/
// OK
/**
* @returns {string | null} Generated text.
*/
Write the any type as `*`
- To express an arbitrary (any) type, use
*. Do not useany. - Still,
*(any) itself is not overused, per "Avoid vague types; write the most specific type you
can" above. Write * (not any) only when the type cannot be narrowed and any is unavoidable.
// NG
/**
* @param {any} value - Value.
*/
// OK
/**
* @param {*} value - Value.
*/
A `*` cast on the right-hand side is prohibited
- **A variable whose declaration carries no type annotation must not be cast with
*on its
right-hand side.** Both /** @type {*} */ (...) and /** @type {Array<*>} */ ([...]) are
prohibited there, as is any written in place of *.
- Nothing about the variable then states a type: the declaration says nothing, and the cast says
any. Every use of that variable downstream is unchecked, so the cast is not a type — it is a
switch that turns the checker off for everything the value reaches.
- The type error the cast silences is evidence. A message such as "
{ Gamma?: undefined }is
not assignable to Record<string, T>" is pointing at the union TypeScript inferred from the
literal, and the fix is to declare what the literal is. Casting deletes the message rather than
the defect.
- **The only
*cast allowed is the temporary one, against a type the project does not own, and
inside the .create() of the MockXxxx stand-in**, so the cast bridges a deliberately partial
literal exactly once and every caller holds the real type. What that class is, where it lives
and what tests it belong to /hoc-jest.
- Against a type the project owns there is no exception. Build the real thing and hand it
over. A cast literal standing in for one of ours declares itself complete while holding two
members, and that claim is one the checker can never test — the type gains a member, the
literal does not, and nothing reports it. Every place that stood the type in has to be found
and corrected by hand, and nothing says which places those are. A real instance follows its own
class instead, so the change reaches the test the way it reaches everything else.
- The one other
*cast allowed is a deliberate type violation in a test: an abnormal-value
case that hands the code under test null, a missing key or another value its contract
refuses, on purpose. The declaration above cases states the contract type, and
/** @type {Array<*>} */ on the literal lets the violation through. It is allowed only where
the type error is the point of the test and plain to see; the test convention (/hoc-jest)
settles which describe() holds those cases.
- Outside these two, in a test this is absolute. The implementation exists by the time its
test is written, so every type the test needs is already declared somewhere in the code under
test. A * there is never "the type cannot be narrowed"; it is "the type was not looked up".
// NG: nothing declares the type, and the cast removes the check
const cases = /** @type {Array<*>} */ ([
{
input: {
errorHash: {
Alpha: AlphaError,
},
},
},
])
// OK: the declaration carries the type
/**
* @type {Array<{
* input: {
* errorHash: Record<string, typeof RenchanGraphqlError>
* }
* }>}
*/
const cases = [
{
input: {
errorHash: {
Alpha: AlphaError,
},
},
},
]
// NG: the cast written where it is used, instead of inside the MockXxxx stand-in
/** @type {GraphqlType.ValidationContext} */
const mockContext = /** @type {*} */ ({
getType: () => null,
reportError: () => {},
})
// NG: a stand-in for a type the project owns, wherever it is written
/** @type {GraphqlType.ServerEngine} */
const mockEngine = /** @type {*} */ ({
env: {
isProduction: () => true,
},
})
- The rule names
constbecause that is the only declaration written:letis prohibited
(see /hoc-statements), and var errors under lint.
A type is stated in three places only
A @type annotation or a cast stands in one of three places, and nowhere else:
- directly above an assignment statement, as the declaration's own
/** @type {T} */ - directly before the right-hand side of an assignment, as
const x = /** @type {T} */ (value) - directly before the value of a
returnstatement, in a method or a function
Never inside a statement: not on an argument, an element of an array, a property value in an
object literal, or the operand of a property access. **Resolve the type in a line of its own,
then run the statement with the resolved value.** Resolving a type and using the value are two
intents; a cast inside the statement packs both into one line, where readability drops sharply.
.create(/** @type {...} */ (...))is a makeshift dodge, never a resolution. The intent
to resolve a type and the intent to run .create() are crammed into one line, and readability
drops sharply. The type is resolved in the line above, and .create() runs with the value it
resolved.
- **In a test, the abnormal-value cases are already let through by the
Array<*>on the
right-hand side of cases.** Nothing inside them is cast again — not the argument of a
factory that builds a refused value, not a property of a case.
// NG: a cast on an argument, inside the statement
return JSON.stringify(
value,
/** @type {Parameters<typeof JSON.stringify>[1]} */ (this.replacer)
)
// OK: the type stated where the value is assigned
const replacer = /** @type {Parameters<typeof JSON.stringify>[1]} */ (this.replacer)
return JSON.stringify(value, replacer)
// NG: a refused value cast again inside an abnormal-value case
const cases = /** @type {Array<*>} */ ([
{
input: {
request: ReportRequest.create(/** @type {*} */ ({
// to: omitted
subject: 'subject-0001',
})),
},
},
])
// OK: the Array<*> on the right-hand side of cases is the only cast
const cases = /** @type {Array<*>} */ ([
{
input: {
request: ReportRequest.create({
// to: omitted
subject: 'subject-0001',
}),
},
},
])
An override is reduced to `/** @override */` only where nothing else is stated
A member that overrides another, and whose JSDoc adds nothing the base does not already
say, is written as the one-line block. **It may be reduced that far only when the block
carries no @param and no @returns** — those two are read by the type checker, and
TypeScript does not inherit them from the base member.
// OK: a getter with no parameters, whose return type the literal already gives
/** @override */
static get errorName () {
return 'DocumentTooDeep'
}
// NG: @param dropped, so the destructured argument becomes an implicit any
/** @override */
static isAcceptable ({
engine,
}) {
// ...
}
- Measured: dropping
@paramfrom an override reportedTS7031on the destructured
binding, and dropping @returns from a member returning a visitor reported TS7006 on
that visitor's own parameters — the return type was what gave them their shape. **Lint
stayed at zero through both**, so nothing but the type checker reports this.
- A description the override adds of its own keeps the block, even where
@paramand
@returns would be redundant: the sentence is the thing being added.
- The one-line form is permitted by
jsdoc/multiline-blocks, which exemptsoverride
among a few others (eslint-jsdoc-rules.md). What
decides whether to use it is this rule, not that exemption.
A `*`-only line is the block's one separator, and it goes in one place
A JSDoc block cannot hold a blank line. Every line inside it carries the leading *
(jsdoc/require-asterisk-prefix), so a line left truly blank is not a wider gap — it is a
lint error, reported alongside jsdoc/check-alignment. What reads as a blank line is a line
carrying nothing but *, and that is the only separator the block has.
It is spent in one place: between the block description and the first tag, where
jsdoc/tag-lines requires exactly one. Nowhere else — not between tags, not before the
closing, and not inside a type literal.
// OK: the one place it goes, between the description and the first tag
/**
* Generate a random text of the given length.
*
* @param {{
* length: number
* }} params - Parameters.
*/
// NG: a `*`-only line used to group the parameters
/**
* @param {{
* ErrorCtor: typeof RenchanGraphqlError
*
* maxDocumentDepth: number
* }} params - Parameters of this constructor.
*/
// OK: the properties stand as one list
/**
* @param {{
* ErrorCtor: typeof RenchanGraphqlError
* maxDocumentDepth: number
* }} params - Parameters of this constructor.
*/
- A grouping worth showing is shown in the code, where a blank line is a blank line:
the argument list of the constructor or the factory carries it, and the JSDoc above
stays a flat list of the same properties.
- Lint places the separator and then stops at the brace.
jsdoc/tag-linescounts the
lines around the tags, so it is what reports a missing separator before the first tag and
a stray one between two tags. Inside a type literal it sees one @param and nothing else,
so a *-only line between two properties is not a line it counts; and
jsdoc/require-asterisk-prefix passes it too, because the line has its asterisk. The
block comes out green, reading as though the grouping were sanctioned, which is why this
convention carries the rest.
Wrap a JSDoc sentence at a clause boundary
- Where a long comment breaks — at a clause, never at a column — belongs to
/hoc-comments. It
is read here for the @param and @returns descriptions, which follow the same break where
they run long.
Do not place a delimiter after each chopped-down property
- When chopping down the
@paramfor named arguments, do not place a semicolon or comma after each property.
// OK
/**
* @param {{
* alpha: number
* beta: number
* }} params - Parameters.
*/
Writing `@typedef`
- Write
@typedefas a block comment of at least three lines. A single-line@typedefis
refused by lint (jsdoc/multiline-blocks).
- The form a multi-line block takes, and the blank line between two blocks, belong to
/hoc-comments.
- Define one
@typedefper block.
// NG: written on a single line
/** @typedef {*} BooleanLike */
// NG: multiple @typedef in one block
/**
* @typedef {*} BooleanLike
* @typedef {{
* id: number
* name: string
* }} UserEntity
*/
// OK: at least three lines, one per block, separated by a blank line
/**
* @typedef {*} BooleanLike
*/
/**
* @typedef {{
* id: number
* name: string
* }} UserEntity
*/
Type-only imports
- To reference a type declared in another module, use a type-only import. Never use the
TypeScript import type statement — it is not available in a JavaScript-only project.
- Two styles exist: the
@importblock tag and the inlineimport('…')expression. **Follow
the style the repository has established, and do not mix both for the same type.** renchan
backends use the inline import('…') expression. If a repository has established neither,
prefer @import.
- One
@importtag per JSDoc block, one source module per block — the same rule as@typedef
above.
// OK: the @import block tag
/**
* @import {
* IncomingMessage,
* } from 'node:http'
*/
// OK: the inline import('…') expression
/**
* @returns {import('./CustomerOrdersBk.js').default} Backup model declaration.
*/
See import-tag.md and
import-expression.md for each style in full.
References
| Reference | Scope | Topic |
| --- | --- | --- |
| eslint-jsdoc-rules.md | Common | ESLint (jsdoc plugin) mapping — follow it and npm run lint passes / where this skill is stricter than lint / intentionally relaxed rules |
| import-tag.md | Common | Type-only import via the @import block tag — placement, named/default forms, source modules, consuming by bare name |
| import-expression.md | Common | Type-only import via the inline import('…') expression — forms, use sites, trade-offs vs @import |