Skip to content

Cannot narrow unknown type to object using typeof #26327

@LinusU

Description

@LinusU

TypeScript Version: 3.0.0

Search Terms: unknown, object, narrow type

Code

const input = null as unknown

if (typeof input === 'number') {
    input
    // input is typed as number here, good!
}

if (typeof input === 'object') {
    input
    // input is typed as unknown here, why not object?
}

Expected behavior:
Expected an unknown type inside a typeof _ === 'object' guard to be of type object.

Actual behavior:
The type stays as unknown

Playground Link:
https://www.typescriptlang.org/play/#src=const%20input%20%3D%20null%20as%20unknown%0A%0Aif%20(typeof%20input%20%3D%3D%3D%20'number')%20%7B%0A%20%20%20%20input%0A%20%20%20%20%2F%2F%20input%20is%20typed%20as%20number%20here%2C%20good!%0A%7D%0A%0Aif%20(typeof%20input%20%3D%3D%3D%20'object')%20%7B%0A%20%20%20%20input%0A%20%20%20%20%2F%2F%20input%20is%20typed%20as%20unknown%20here%2C%20why%3F%0A%7D%0A

Related Issues:
#25720

This was mentioned in the comments here: #25720 (comment), but I couldn't find a standalone issue for it. Thus I created this issue to get more visibility.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions