0

I have the typescript error saying: Variable 'trait' is used before being assigned.

Thats down at pickedTraits.push()

I dont get it, i declared trait and assigned it on the begin of the loop, why does typescript complain about?

It works when i put it outside the while loop, but i need it inside of it

  layers.map((layer) => {
      let stop = true
      let trait: TraitInterface
      while (stop) {
        trait = utilsService.pickRandomTrait(layer.traits)
        let reachedMaxmimum = alreadyPicked.findIndex(
          ({ traitId, appeared }) =>
            trait._id.equals(traitId) && (appeared ?? 0) >= trait.showUp
        )
        if (reachedMaxmimum !== -1) {
          layer.traits = layer.traits.filter(
            ({ _id }) => !_id.equals(alreadyPicked[reachedMaxmimum].traitId)
          )
        } else {
          alreadyPicked.push({
            traitId: trait._id,
            appeared: 1,
          })
          stop = false
          continue
        }
      }

      pickedTraits.push({
        name: trait.name,
        rarity: trait.rarity,
        layerName: layer.name,
      })
      return drawingService.addLayer(
        context,
        trait.src,
        size.height,
        size.width
      )
    })
bill.gates
  • 14,145
  • 3
  • 19
  • 47

1 Answers1

0

I have fixed the problem with the ! non-null assertion operator

let trait!: TraitInterface

Now it works

Here is the answer: In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

bill.gates
  • 14,145
  • 3
  • 19
  • 47