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

Viewed 58

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.)

3 Answers

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);
Related