typescript - "Variable is used before being assigned"(TS2454) 没有帮助的模式

标签 typescript

考虑以下代码模式,

class stuff {
    public id: string;
    public uid: number;
    constructor(parameter: string){
        this.id = parameter;
    }
    public getUID(): number {
        return Date.now();
    }
}

let ids: number[]; /* 1: Here variable is not assigned */
for ( let i = 0; i < 100; i++){
    ids[i] = new stuff(i.toString()).getUID();
    /* 2: Here ids[i] is used before initialized */
}

在这样的模式下,typescript 不会用 "strict": true 编译。

我可以做 let ids:number[] | undefined 但这失去了使用 typescript 的值(value)。

是否有任何其他模式可以实现相同的行为?

谢谢。

最佳答案

let ids: number[] = [];
for ( let i = 0; i < 100; i++){
    ids.push(new stuff(i.toString()).getUID());
}

关于typescript - "Variable is used before being assigned"(TS2454) 没有帮助的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46686958/

相关文章:

javascript - 字符串不可分配给 onMouseEvent

javascript - 如何扩展依赖项的 TypeScript 接口(interface)

javascript - 从本地存储中保存和检索日期

typescript - 如何借助 Automapper (TypeScript) 映射充满不同 DTO 的数组条目?

javascript - native 元素的大小为零

typescript - 如何创建具有动态字段名称的 Formik YUP 架构?

angular - 如何静音 "The feature name "路由器“状态中不存在...”ngrx/router-store 警告

reactjs - 无法在 Typescript 中模拟 axios 实例

reactjs - 使用具有日期时间本地类型的material-ui TextField 时是否会阻止输入清除?

node.js - 如何在 TypeScript 中动态访问对象属性