Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda