【问题标题】:Typecast JS variable to Typescript Interface将 JS 变量类型转换为 Typescript 接口
【发布时间】: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


    【解决方案1】:

    在运行时,您如何保证boxIBox 而不是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
    }  
    

    希望这是有道理的。祝你好运。

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2021-01-17
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 2018-10-27
      • 2017-11-26
      相关资源
      最近更新 更多