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
Related Issues:
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 29
- Comments: 29 (6 by maintainers)
@MufidJamaluddin duplicate of #7719
Workaround is use
kelas!.iskelasI 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:Apparently, the compiler doesn’t understand that
atLeastOneButtonis performing a not-undefined check for the samebuttonsvariable.Playground link https://www.typescriptlang.org/play/?ts=Nightly#code/C4TwDgpgBAIglgQwDYHsDmAFATisBnKAXigG8AoKKAIwFdhgUA7PAfgC5SLKows4BbBFhAcqKFEggJGAbi6U8EAMZMAJkJDtq4ydLmUAvnKNkyAMxqMlwOE1iJUaABQlqdBsygGO8ZOmy4eACUnNxQKszAUAjAADJSeMAA8owQAELudsS09EwEAISExJaqEGZwqapQAGTVbrnMAHS8AhpQhcWMpeWVcvJQcGZQTjHxCIkp6ZmMIeRhlBGJUEgIVBBIRPUeeM18gsL63AZkBkA
Hello All,
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:-
While using this interface Blog in our code if we are trying to do some loop on Blog.contents Eg:-
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:-
This is one way to resolve this warning.
Happy Coding!
@RyanCavanaugh did you link the wrong issue? That one has been closed since 2018.
Another example below in case it helps.
http://www.typescriptlang.org/play/?noImplicitReturns=false#code/JYOwLgpgTgZghgYwgAgArAQawK4AcAickAzsgN4BQyyA2phAJ4BcyxYUoA5gLotm31myENgC2AI2i9khSMgC+yAD7JsIACYQYoCOoryKVZDDUIwwAPYhjodeix5ZKABS4MOAkQjEW9j0+IAGmQ4dXUobx9Wdi5g2wgADxYRCWgAShYnZVUNLR11ciNqYBhkZwBCNwdPEhpQ8MjuZRVK90cvYjqwiOJibhp4hO40wuox5AiwbCgQIoVDccnp6yr-Dq6G3v7B7iMDIA
@gkamperis Yeah, for the complier,
num !== undefined ? (num > 0) : falseandnum > 0comes 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
why is this not allowed?
playground