In my JavaScript project, I am utilizing TypeScript and JSDOC for code validation against the TS compiler.
When analyzing my code, the TS compiler identifies an error in the following snippet:
interface IBox {
idx: number;
}
interface IBoxes {
get(idx?: number): IBox | IBox[];
}
class Box implements IBox {
constructor() {
this.idx = 0;
}
}
class Boxes {
constructor() {
this.boxes = [new Box(0)];
}
/**
* @param {number} idx
*/
get(idx) {
if (idx) {
return this.boxes.find(b => b.idx === idx);
}
return this.boxes;
}
/**
* @param {IBox} value
*/
set(value) {
this.boxes.push(value);
}
}
const boxes = new Boxes();
/** @type {IBox} */
const box = boxes.get(0);
box.idx; // Property "idx" does not exist on type "IBox" | "IBox[]"
// Property 'idx' does not exist on type 'IBox[]
(box as IBox).idx; // Using type casting to suppress the error
While type casting may work, I am curious if there is a way to address this issue in plain JavaScript without the as
keyword. Are there any JSDOC properties or other techniques that can be used to achieve the same outcome in a JavaScript project?