Skip to content

JSDocs don't support properties on functionsΒ #56615

Open

Description

πŸ” Search Terms

JSDoc @Property @callback @typedef

βœ… Viability Checklist

⭐ Suggestion

Currently JSDoc doesn't support defining properties on functions. This prevents JavaScript users from paralleling Typescript functionality. In particular, it prevents describing flags such as the type property on Redux Action Creators.

To support these, JSDoc would need to support defining function interfaces that include string properties, such as:

/**
 * @typedef {{
 *   (arg: string): { type: string, payload: string };
 *   type: string;
 * }} ActionCreator
 */

/** @type {ActionCreator} */
const createFoo = (arg) => ({ type: createFoo.type, payload: arg });
createFoo.type = 'fooAction';

Ideally we could also extend @callback to include @property values, but this may stretch JSDoc beyond its limits.

πŸ“ƒ Motivating Example

JSDocs are finally in parity with TypeScript, when it comes to adding properties to functions. Previously, if you wanted to add a property to a function, you'd need to import a type from a TypeScript file that looks like this:

type PayloadCreator<Payload> = {
  (payload: Payload): { type: string; payload: Payload };
  type: string;
};

const createNumericPayload: PayloadCreator<number> = (payload) => ({ type: createPayload.type, payload });
createNumericPayload.type = 'numericPayload';

Now you can do it directly in your JavaScript, with

/**
 * @template Payload
 * @typedef {{
 *   (payload: Payload): { type: string; payload: Payload };
 *   type: string;
 * }} PayloadCreator
 */

/** @type {PayloadCreator<number>} */
const createNumericPayload = (payload) => ({ type: createPayload.type, payload });
createNumericPayload.type = 'numericPayload';

πŸ’» Use Cases

  1. What do you want to use this for?
    This allows me to add properties to a function in JavaScript in the same way that I can in TypeScript.
  2. What shortcomings exist with current approaches?
    Currently I must import from TS files, meaning I can't have JS-only environment.
  3. What workarounds are you using in the meantime?
    Using @typedef {import} to pull the definition from a TS file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

BugA bug in TypeScriptExperience EnhancementNoncontroversial enhancementsFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions