Typescript code works but throws Object is possibly undefined error

249 Views Asked by At

I'm trying to implement a queue structure in my typescript class. I have a queue class.

class Queue implements IQueue {

private storage: number[] = [];

constructor(private capacity: number = 3) {}

enqueue(rssi: number){
    if(this.size() == this.capacity) throw new Error("Has reached max capacity");
    this.storage.push(rssi);        
}

dequeue(): number | undefined{
    return this.storage.shift();

}

size(): number{
    return this.storage.length;
}

signalMean(): number{
    var mean: number = 0;
    this.storage.forEach(rssi => mean = mean + rssi);
    return mean;
}

}

So I tried to initialize a queue:

var init = new Queue(3);

and use it to here

if(signals.get(sender.id) == undefined) signals.set(sender.id, init); 

When I try to add this codes like in below:

  if(signals.get(sender.id)?.size() < signals.get(sender.id).capacity) {
        signals.get(sender.id).enqueue(sender.signal);
    } else {
        signals.get(sender.id).dequeue();
        signals.get(sender.id).enqueue(sender.signal);
    }

I get Object is possibly 'undefined'. error although I checked and initialized it with if(signals.get(sender.id) == undefined) signals.set(sender.id, init); line.

But when I control it with log it works... How can I fix this issue?

1

There are 1 best solutions below

1
MoxxiManagarm On

if(signals.get(sender.id)?.size() < signals.get(sender.id).capacity) {

The problem is, that with the safe-access-operator (?) you tell the compiler, that signals.get(sender.id)?.size() can be undefined. As a result you would compare this undefined value with the < operator. Easiest fix is to remove the safe-access-operator and handle the not existing case separately.