I just noticed that we can get IDE intellisense autocompletion through JSDoc type hints like this (from Vite config documentation):
/** @type {import('vite').UserConfig} */
export default {
// ...
}
Is the import('vite')
type functionality part of JSDoc? I've never seen this used before, so just curious how it works.
Can we get autocompletion for any type in a plain JavaScript project by using @type
annotations like this?
All type hint are supplied by TypeScript's language server, enabled by default in VSCode & widely available in other editors.
JSDoc is just a standardized syntax for writing documentation in JS, functionally, it does nothing. The TS language server, however, has implemented a subset of the JSDoc syntax which will allow you to type your JS code without authoring TS (.ts
). This will match TypeScript behavior in most cases, though there's a few odd cases where JSDoc trails behind or lacks support for a few features.
As linked above (https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html), yes, you can use type comments to get autocompletion hints in plain JS using this:
/** @type {'foo' | 'bar'} */
const myString = 'baz';
// ^ Type '"baz"' is not assignable to type '"foo" | "bar"'
The import(module)
bit allows you to access types, as of course you cannot otherwise import types into JS modules.