Closed
Description
Bug Report
π Search Terms
typeof object, null checks, narrowing object, narrow generics
π Version & Regression Information
All
- This is the behavior in every version I tried
β― Playground Link
Playground link with relevant code
π» Code
function func<T>(obj: T): boolean {
if (obj && (typeof obj === 'object') && obj.hasOwnProperty('xyz')) {
return true;
}
return false;
}
declare const testVariable: unknown;
if (testVariable !== null && (typeof testVariable === 'object') && testVariable.hasOwnProperty('xyz')) {
}
if ((typeof testVariable === 'object') && testVariable !== null && testVariable.hasOwnProperty('xyz')) {
}
π Actual behavior
The generic function doesn't infer that obj
must be an object
of some sort.
The first if doesn't infer that testVariable
can't be null.
π Expected behavior
The generic function should infer that T
is an object
because we did a null check and checked typeof
.
Both ifs should infer that testVariable
can't be null.
Notes
Is this just me missing some 'known behaviour' typescript has? the two conditions seem to depend on ordering, maybe thats just a known thing i was unaware of (i.e. by design)?