Search code examples
javascriptintellij-ideajsdoclwc

Can you defined a typedef and still use the spread operator to iterate using map()?


I'm trying to define an Object using JSDoc typedefs. So given the following type definition:

/**
 * @typedef AccommodationData
 * @type {Object}
 * @property {string} id
 * @property {string} name
 * @property {boolean} selected
 */

I would define the type of accommodations. Then I want to be able to iterate over this using the map method and the spread operator to keep things concise.

import { LightningElement } from 'lwc';

export default class AccommodationList extends LightningElement {
    // --- Private properties ---

    /** @type {AccommodationData[]} */
    accommodations = [];

    // --- Getters ---
    
    /**
     * Get Accommodation Data with applied selections.
     * @returns {AccommodationData[]}
     */
    get accommodationsData() {
        return this.accommodations.map((a) => ({
            ...a,
            selected: this.selectedId === a.id
        }));
    }
}

When I do this, my IDE gives me the following warning:

Returned expression type (any & {selected: boolean})[] is not assignable to type AccommodationData[]   Type any & {selected: boolean} is not assignable to type AccommodationData     Type number is not assignable to type undefined

Is there a way to use this typedef with this method and not throw the warning from the IDE? (Error pictured below)

enter image description here


Solution

  • The answer is to make these properties optional. Otherwise, they are required whenever defining a new instance of the Type.

        /**
         * @typedef AccommodationData
         * @type {Object}
         * @property {string} [id]
         * @property {string} [name]
         * @property {boolean} [selected]
         */