Skip to content

Type narrowing generics/unknown doesn't seem to work with typeof and null checkΒ #43997

Closed
@43081j

Description

@43081j

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions