Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot narrow unknown type to object using typeof #26327

Closed
LinusU opened this issue Aug 9, 2018 · 3 comments
Closed

Cannot narrow unknown type to object using typeof #26327

LinusU opened this issue Aug 9, 2018 · 3 comments
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@LinusU
Copy link
Contributor

LinusU commented Aug 9, 2018

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.

@ghost ghost added the Bug A bug in TypeScript label Aug 9, 2018
@RyanCavanaugh RyanCavanaugh added this to the TypeScript 3.1 milestone Aug 9, 2018
@felipeochoa
Copy link

It should be null | object, no?

@MaartenStaa
Copy link

Or maybe null | object | unknown[].

> typeof null
'object'
> typeof {}
'object'
> typeof []
'object'

@RyanCavanaugh
Copy link
Member

unknown[] is a subtype of object, so redundant to appear in a union type with it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

5 participants