TypeScript: Object is possibly 'undefined'

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms: Object undefined

Code turn strictNullChecks on

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
type EventType = 'click' | 'dblclick'

const handlerMap: { [P in EventType]?: any[] } = {}

function addHandler<P extends EventType>(evType: P) {
  const handlerList = handlerMap[evType] || []
  handlerList.push({}) // Error here: Object is possibly 'undefined'
  handlerMap[evType] = handlerList
}

Expected behavior: No Error

Actual behavior: Shows Error

Playground Link: http://www.typescriptlang.org/play/#src=type EventType %3D ‘click’ | ‘dblclick’ const handlerMap%3A { [P in EventType]%3F%3A any[] } %3D {} function addHandler<P extends EventType>(evType%3A P) { const handlerList %3D handlerMap[evType] || [] handlerList.push({}) %2F%2F Error here%3A Object is possibly ‘undefined’ }

Related Issues:

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 29
  • Comments: 29 (6 by maintainers)

Commits related to this issue

Most upvoted comments

@MufidJamaluddin duplicate of #7719

Workaround is use kelas!.iskelas

Screenshot 2019-08-06 at 15 45 00

I got the exact same issue since upgrading to newer version 3.5.2. I honestly don’t know what to do as this worked for ages. Forcing with ! is no option for me.

Another example, tried on 3.7.0-dev.20190928:

type DialogProps = {
  buttons?: {
    primary: boolean;
    secondary?: boolean;
  };
};

function Dialog({ buttons }: DialogProps) {
    const atLeastOneButton = buttons !== undefined;

    if (atLeastOneButton) {
      const label = buttons.primary; 
      // throws "Object is possibly 'undefined' over `buttons`
    }
}

Apparently, the compiler doesn’t understand that atLeastOneButton is performing a not-undefined check for the same buttons variable.

Playground link https://www.typescriptlang.org/play/?ts=Nightly#code/C4TwDgpgBAIglgQwDYHsDmAFATisBnKAXigG8AoKKAIwFdhgUA7PAfgC5SLKows4BbBFhAcqKFEggJGAbi6U8EAMZMAJkJDtq4ydLmUAvnKNkyAMxqMlwOE1iJUaABQlqdBsygGO8ZOmy4eACUnNxQKszAUAjAADJSeMAA8owQAELudsS09EwEAISExJaqEGZwqapQAGTVbrnMAHS8AhpQhcWMpeWVcvJQcGZQTjHxCIkp6ZmMIeRhlBGJUEgIVBBIRPUeeM18gsL63AZkBkA

Hello All,

The object is possibly ‘undefined’,

This warning is shown by the editor when we provide the body definition of some variable in the form of the interface and add some of the fields as optional

Eg:-

interface Blog {
  autherName: string;
  contents?: any[],
  id: string
}

While using this interface Blog in our code if we are trying to do some loop on Blog.contents Eg:-

const newBlog: Blog = JSON.parse(blog);
for (const content of newBlog.contents) {`
   console.log("content ", content );
}

This will error in for loop declaration for (const content of newBlog.contents) because we have said in an interface that contents property in Blob object can be or cannot be there hence we first need to check in code if the property is present then we should use it. As follows

Eg:-

if (newBlog.contents && newBlog.contents.length > 0) {
    for (const content of newBlog.contents) {
      console.log("content ", content );
   }
}

This is one way to resolve this warning.

Happy Coding!

@RyanCavanaugh did you link the wrong issue? That one has been closed since 2018.

@gkamperis Yeah, for the complier, num !== undefined ? (num > 0) : false and num > 0 comes out the same result. But for progammers, it’s obvious the first one is better.

TS was made for JS users to make less mistakes and that’s how TS did it.

Consider this one

checkIsPositive(num: number | undefined): boolean {
        return !(num <= 0)
}   

why is this not allowed?

checkIsPositive(num: number | undefined): boolean {
        return num > 0
    }    

playground