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

228
Vistas
Why is the following function throwing Object is possibly 'undefined'?

I'm trying to create a tiny library with the following structure:

library('input').method()

This is the code (the addQuotes method adds quotes to the string input):

const library = function (text: string) {
  interface ValueObject {
    addQuotes?: Function
  } // Without this, I get "Property 'to' does not exist on type '{}'."                                                                                                                                                 

  const options: ValueObject = {}

  options.addQuotes = function () {
    if (!text) return ''
    return `"${text}"`
  }

  return options
}

const result = library('test').addQuotes()
console.log(result)

Right now, TypeScript is underlying this bit:

library('test').addQuotes() 

Telling me this:

Object is possibly 'undefined'.

What could be the problem and how to fix it?

https://jsbin.com/vonawucada/1/edit?js,console

(The code runs here, but in my VS Code setup, I do get the TypeScript error.)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

the reason you get Object is possibly 'undefined' is because your addQuotes property is optional, see https://www.typescriptlang.org/docs/handbook/interfaces.html#optional-properties

the solution is one of the following:

  1. remove the optional ? modifier from the property
  2. add ! modifier when accessing the property telling TS that you know that it's assigned (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization): library('test').addQuotes!()
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is with your return type of library module. The return type of the library is ValueObject which is a private interface. It means its scope is limited to the library module. Typescript will never understand the return type of private interface.

The solution would be to move the ValueObjet interface out of the library module scope and make it public so that typescript can understand that what is the return type of the library function.

interface ValueObject {
  addQuotes: Function;
}

const library = function (text: string) {
  const options = {} as ValueObject;

  options.addQuotes = function () {
    if (!text) return "";
    return `"${text}"`;
  };

  return options;
};

const result = library("test").addQuotes();
console.log(result);
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is because you are defining addQuotes as an optional function inside the interface using the (?) symbol. Later when you try using it on an object you would need to check if its undefined first before using it.

You can read more here: https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties

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