skip to Main Content

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


  1. Chosen as BEST ANSWER

    I made a function from Cody Duong's answer to be able to reuse it easier.

    function getBeat(name:string):Beat {
      const beatType = beatTypes.get(name);
    
      if (beatType != undefined) return beatType;
      else throw console.error(`No beat type with name ${beatType}`)
    }
    

  2. You have to extract out beatTypes.get('rest') to a variable, then typescript conditional flow will work correctly

    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++) {
            const beatType = beatTypes.get('rest');
            // ^^^ Add this line
            if (beatType != undefined) beats.push(beatType);
            else console.error("Beat type doesn't exist");
          }
        }
    
        this.beats = beats;
      }
    }
    

    View on TS Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search