Search code examples
javascriptjsdoc

How to type keyof instace in JSDOC similarily to TS?


How can I type keyof instance in Javascript (JSDOC) similarily to Typescript?

TS is just fine:

const a1 = new Car('Audi A1', 4, Power.solar);
const a380 = new Plane('Airbus A380', 800, 4);

function showProperty<T>(thing: T, prop: keyof T) {
    console.log(`${String(prop)}:`, thing[prop]);
}

showProperty(a1, 'power');
showProperty(a380, 'engines');

link to full TS code

but I don't know how to do it with jsdoc:

const a1 = new Car('Audi A1', 4, 'petrol');
const a380 = new Plane('Airbus A380', 800, 4);

/**
 * @param {Thing} thing
 * @param {keyof Thing} prop
 */
function showProperty(thing, prop) {
    console.log(`${String(prop)}:`, thing[prop]);
}

showProperty(a1, 'capacity'); // I want to see the "power" property here...!
showProperty(a380, 'capacity'); // I want to see the "engines" property here...!

link to full JS code


Solution

  • With JSDoc annotations in TypeScript, you can use the @template tag to declare a type parameter for the function. This is similar to the TypeScript syntax of using angle brackets (<T>) to define a type parameter.

    /**
     * @template T
     * @param {T} thing
     * @param {keyof T} prop
     */
    function showProperty(thing, prop) {
        console.log(`${String(prop)}:`, thing[prop]);
    }
    

    VSCode and other code editors should now be able to see all the properties

    Link to modified JS code