Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda