microsoft / microsoft/TypeScript

JSDocs don't support properties on functions

Open
#56,615 12 comments 2 reactions 1 assignee View on GitHub

@sandersn is already working on this.

Since Dec 1, 2023.

Bug Domain: JSDoc Experience Enhancement
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.