Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A pattern where "Variable is used before being assigned" (TS2454) is not helpful

Tags:

typescript

Consider the following code pattern,

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 */
}

In such a pattern, typescript won't compile with "strict": true.

I could do let ids:number[] | undefined but that loses the value of using typescript.

Is there any other pattern with which I can achieve the same behaviour?

Thanks.

like image 776
kalpa Avatar asked Oct 24 '25 22:10

kalpa


1 Answers

let ids: number[] = [];
for ( let i = 0; i < 100; i++){
    ids.push(new stuff(i.toString()).getUID());
}
like image 197
André Avatar answered Oct 26 '25 20:10

André