Skip to content

Narrowing unknown by typeof object to object | null #26828

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

Merged
merged 1 commit into from
Sep 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14925,6 +14925,9 @@ namespace ts {
return type;
}
if (assumeTrue && !(type.flags & TypeFlags.Union)) {
if (type.flags & TypeFlags.Unknown && literal.text === "object") {
return getUnionType([nonPrimitiveType, nullType]);
}
// We narrow a non-union type to an exact primitive type if the non-union type
// is a supertype of that primitive type. For example, type 'any' can be narrowed
// to one of the primitive types.
Expand Down
14 changes: 14 additions & 0 deletions tests/baselines/reference/narrowUnknownByTypeofObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//// [narrowUnknownByTypeofObject.ts]
function foo(x: unknown) {
if (typeof x === "object") {
x
}
}


//// [narrowUnknownByTypeofObject.js]
function foo(x) {
if (typeof x === "object") {
x;
}
}
13 changes: 13 additions & 0 deletions tests/baselines/reference/narrowUnknownByTypeofObject.symbols
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
=== tests/cases/compiler/narrowUnknownByTypeofObject.ts ===
function foo(x: unknown) {
>foo : Symbol(foo, Decl(narrowUnknownByTypeofObject.ts, 0, 0))
>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13))

if (typeof x === "object") {
>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13))

x
>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13))
}
}

16 changes: 16 additions & 0 deletions tests/baselines/reference/narrowUnknownByTypeofObject.types
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
=== tests/cases/compiler/narrowUnknownByTypeofObject.ts ===
function foo(x: unknown) {
>foo : (x: unknown) => void
>x : unknown

if (typeof x === "object") {
>typeof x === "object" : boolean
>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
>x : unknown
>"object" : "object"

x
>x : object | null
}
}

6 changes: 6 additions & 0 deletions tests/cases/compiler/narrowUnknownByTypeofObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// @strictNullChecks: true
function foo(x: unknown) {
if (typeof x === "object") {
x
}
}