Typescript: Cannot narrow unknown type to object using typeof

Created on 9 Aug 2018  ·  3Comments  ·  Source: microsoft/TypeScript

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: https://github.com/Microsoft/TypeScript/issues/25720#issuecomment-406167061, but I couldn't find a standalone issue for it. Thus I created this issue to get more visibility.

Bug Fixed

Most helpful comment

It should be null | object, no?

All 3 comments

It should be null | object, no?

Or maybe null | object | unknown[].

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

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

Was this page helpful?
0 / 5 - 0 ratings