Search code examples
angulartypescript

TypeScript: variable is possibly 'undefined'.ts(18048)


In one of my Angular projects, I have one interface in userinterface.ts

export interface Done {
    wordlen: number;
    word: string;    
};

which I am using to populate a array

donearr: Done[] = [];
let fill:Done  = {  wordlen: 4, word: "word" }
this.donearr.push(fill)    

It is working till here. But when I take the last object from array for some processing it throws error.

let v_last = this.donearr.pop()        
console.log(v_last) // this displays the array content
console.log(v_last.wordlen) // this gives error. 
                            // 'v_last' is possibly 'undefined'.ts(18048)
                            // let v_last: Done | undefined

I have tried let v_last: Done = this.donearr.pop() but that also gives error.

Type 'Done | undefined' is not assignable to type 'Done'.
  Type 'undefined' is not assignable to type 'Done'.ts(2322)

Where I am taking it wrong ?


Solution

  • Since the method Array.pop() possibly returns undefined. Typescript will make you check it out. In this case you are sure Array.pop() will return a non-undefined value, so instead of writing let v_last = this.donearr.pop() you can write let v_last = this.donearr.pop()! (notice the "!"-mark). This means that you are sure this code will always return something.

    Make sure to check out: https://www.typescriptlang.org/tsconfig/#strictNullChecks