Documenting options objects with JSDoc and TypeScript in Visual Studio Code
If you’re writing JavaScript in Visual Studio Code, using a jsconfig.json
file to use VS Code’s internal version of TypeScript for type checking without having to take on any devDependencies
or adding a build step, and you’ve just added an options object to a function, this is how you document it with the minimal amount of JSDoc to get both the appropriate type checking and pretty documentation in VS Code when you hover over the function definition:
/**
* @param {{checkMx: boolean}} options options:
* - `checkMx` — if `true`, also redirect if the `mx=1` parameter is missing
* @returns {boolean} `true` if this call replaces the current location
*/
function redirectToTwitter({checkMx}) {
// ...
}
Declare the options object with a @param
tag - inside the curly braces, use TypeScript type declaration syntax, so for an options object it will define an object with properties.
The function I happened to be writing above was a simple single-option example, but you can use multiple lines in the type declaration if you need to, for example here’s a more complicated options object (without documentation, for brevity):
/**
* @param {string} selector
* @param {{
* name?: string
* stopIf?: () => boolean
* timeout?: number
* context?: Document | HTMLElement
* }?} options
* @returns {Promise<HTMLElement | null>}
*/
function getElement(selector, {
name = null,
stopIf = null,
timeout = Infinity,
context = document,
} = {}) {
// ...
}
After providing a name for the options object, put a description on the same line:
/**
* @param {{checkMx: boolean}} options options:
*/
The description itself is superfluous, but its presence matters, as it serves as the first line of documentation. As a result, instead of taking the first line of your actual options documentation and displaying it inline, VS Code will render the rest as whatever Markdown you provide.
This allows you to use a Markdown list to document the options themselves - to match VS Code’s other documentation formatting, you can use code
for the option name and separate its description with an em-dash (—):
/**
* @param {{checkMx: boolean}} options options:
* - `checkMx` — if `true`, also redirect if the `mx=1` parameter is missing
*/
This results in the following documentation when you hover over references to the function in VS Code: