Hacker News new | ask | show | jobs
by jeroenhd 556 days ago
I've seen several ways of annotating Javascript that IDEs seem to understand. They usually involve using comments before fields, classes, or functions.

The most compliant one seems to be using [JSDoc](https://jsdoc.app/). JSDoc is mostly intended for generating documentation. However, the Typescript compiler can validate types (and can even interoperate with Typescript definitions), if you configure it as such.

In scenarios where you HAVE to write raw Javascript but still would like to do some type validation, this is probably the best solution.

It looks a bit like this:

    /**
     * Fiddle the widget
     * @param {WidgetThing} The widget to fiddle
     */
    function fiddleWidget(widget) {
This is a type hint that asserts that `widget` is of type `WidgetThing`.

JSDoc also works in the middle of a method:

    /** @type {Foo} */
    const foo = widget.fetchFoo();
This asserts that `foo` is of type `Foo`. This could in theory also be derived from the return value of `widget.fetchFoo()` of course.

JSDoc also has arbitrary type definitions:

    /**
     * @typedef Foo
     * @type {object}
     * @property {WidgetThing} parent - the parent that created this Foo.
     * @property {string} name - the name of this Foo.
     */
I would stick to transpiling Typescript myself, but I've also seen use cases where that's simply not an option.