I am using typescript and am trying to push a map value(custom class caled beat) to a beat array and am getting this error, Argument of type ‘Beat | undefined’ is not assignable to parameter of type ‘Beat’. Code
//*Beat
class Beat {
hexValue: number;
symbol?: string;
constructor(hexValue: number, symbol?: string) {
this.hexValue = hexValue;
this.symbol = symbol;
}
}
//Empty beat
let beatTypes = new Map<string, Beat>();
beatTypes.set('rest', new Beat(0x0000000000000000));
console.log(typeof(beatTypes.get('rest')));
let rest = new Beat(0x0000000000000000);
//*Staff
//Staff horizontal lines
class Staff {
beats:Beat[];
constructor(beats:Beat[]){
//Remove excess beats
if (beats.length > 4)
beats = beats.slice(0, 4);
//Set empty beats as rests
else if (beats.length < 4){
for (let index = 0; index <= 4 - beats.length; index++)
if (beatTypes.get('rest') != undefined)
beats.push(beatTypes.get('rest'));
else
console.error("Beat type doesn't exist");
}
this.beats = beats;
}
I was hopping to be able to have the map not retern undifind values as this will help with further development.
2
Answers
I made a function from Cody Duong's answer to be able to reuse it easier.
You have to extract out
beatTypes.get('rest')
to a variable, then typescript conditional flow will work correctlyView on TS Playground