我在js项目中使用typescript和jsdoc,并根据ts编译器验证代码。
以下代码引发TS验证错误:
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; // Suppressing the error
我知道我可以输入cast来处理这种情况。但由于这是一个js项目,我怎么能只使用普通的旧js,因为它缺少 as 关键字?有什么方法可以使用jsdoc属性或其他东西来实现它吗?
as
在运行时,您如何保证 box 是一个 IBox 而不是 IBox[] 或 undefined ?让编译器相信 idx 它会让你:
box
IBox
IBox[]
undefined
idx
if (box) { if ('idx' in box) { box.idx; // okay, box is now recognized as IBox } else { box[0].idx; // okay, box is recognized as IBox[] } } else { // no box }
希望这是有道理的。祝你好运。