简体   繁体   中英

An object is created without a method of a class. Typescript error: Cannot invoke an object which is possibly 'undefined'. ts(2722)

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.

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
}

You can either add the function to the object you're creating

let b: A = {
  id: 9,
  isIdZero: () => false,
}

Or you can stop trying to call this an A, and just let it be an object with an id that's a number:

let b = {
  id: 9,
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM