Home > other >  An object is created without a method of a class. Typescript error: Cannot invoke an object which is
An object is created without a method of a class. Typescript error: Cannot invoke an object which is

Time:11-03

Good evening! I am newbie in javascript and typescript.

I can't understand something. I carefully typed my code and the situation appeared. I can't imagine, why, through it's something basic. Look:

class A {
    id: number;
    constructor(id:number){
        this.id=4;
    }
    isIdZero?():boolean{
        if(this.id===0)
            return true;
        else 
            return false;
    }
}

let a : A= new A(0);
let b : A={
    id:9
}

alert(b.isIdZero());

This code makes an error "Cannot invoke an object which is possibly 'undefined'. ts(2722)"

Why? Function equals to what typed in {}, isn't it?

How can I correct it?

My question is probably so primitive that I didn't find anything.

CodePudding user response:

isIdZero?():boolean{

The question mark here means you're defining isIdZero so it may be undefined, instead of being a function. Since it might be undefined, typescript won't let you call it unless you check it first. Eg:

if (b.isIdZero) {
  alert(b.isIdZero());
}

If you want isIdZero to be a mandatory property, then remove the question mark. However, this change will cause the following code to start showing a type error, since the object doesn't have all the properties it needs to be an A:

let b : A={
    id:9
}

CodePudding user response:

the ? operator you are using after isIdZero? tells typescript that you expect a possibility of this property being undefined.

It doesn't seem like that's necessary, so you can remove that.

  • Related