How do I tell a javascript variable that it can't be undefined, at its creation

Viewed 35
getPersonneById(id: number): Personne{
    const personne = this.personnes.find( personne => {
      return personne.id == id;
    });
    return personne;
}

It shows this error : Impossible to assign type 'Person | undefined' to type 'Person'. Impossible to assign type 'undefined' to type 'Person'.

I also did this one and it worls but that's not what I really want:

getPersonneById(id: number): Personne{
    const personne = this.personnes.find( personne => {
      return personne.id == id;
    });
    if(typeof personne !== 'undefined'){
      return personne;
    }else{
      return this.personnes['0'];
    }
}

personnes is an array.

So what I want to know is if there is a way to tell to my var that it couldn't be undefined or some better solution

1 Answers

If you know that a value will always be found by find, use the non-null assertion operator to express that guarantee in TypeScript:

return personne!;
Related