Description
π Search Terms
JSDoc @Property @callback @typedef
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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
- 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. - What shortcomings exist with current approaches?
Currently I must import from TS files, meaning I can't have JS-only environment. - What workarounds are you using in the meantime?
Using@typedef {import}
to pull the definition from a TS file