【发布时间】:2018-11-28 12:20:27
【问题描述】:
我在我的 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 属性或其他东西使它工作?
【问题讨论】:
标签: typescript casting jsdoc