Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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,
}
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!