Skip to content

Commit f1a179a

Browse files
committed
Narrowing unknown by typeof object to object | null
Fixes #26327
1 parent cbdfc01 commit f1a179a

File tree

5 files changed

+52
-0
lines changed

5 files changed

+52
-0
lines changed

src/compiler/checker.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14925,6 +14925,9 @@ namespace ts {
1492514925
return type;
1492614926
}
1492714927
if (assumeTrue && !(type.flags & TypeFlags.Union)) {
14928+
if (type.flags & TypeFlags.Unknown && literal.text === "object") {
14929+
return getUnionType([nonPrimitiveType, nullType]);
14930+
}
1492814931
// We narrow a non-union type to an exact primitive type if the non-union type
1492914932
// is a supertype of that primitive type. For example, type 'any' can be narrowed
1493014933
// to one of the primitive types.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
//// [narrowUnknownByTypeofObject.ts]
2+
function foo(x: unknown) {
3+
if (typeof x === "object") {
4+
x
5+
}
6+
}
7+
8+
9+
//// [narrowUnknownByTypeofObject.js]
10+
function foo(x) {
11+
if (typeof x === "object") {
12+
x;
13+
}
14+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
=== tests/cases/compiler/narrowUnknownByTypeofObject.ts ===
2+
function foo(x: unknown) {
3+
>foo : Symbol(foo, Decl(narrowUnknownByTypeofObject.ts, 0, 0))
4+
>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13))
5+
6+
if (typeof x === "object") {
7+
>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13))
8+
9+
x
10+
>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13))
11+
}
12+
}
13+
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
=== tests/cases/compiler/narrowUnknownByTypeofObject.ts ===
2+
function foo(x: unknown) {
3+
>foo : (x: unknown) => void
4+
>x : unknown
5+
6+
if (typeof x === "object") {
7+
>typeof x === "object" : boolean
8+
>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
9+
>x : unknown
10+
>"object" : "object"
11+
12+
x
13+
>x : object | null
14+
}
15+
}
16+
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// @strictNullChecks: true
2+
function foo(x: unknown) {
3+
if (typeof x === "object") {
4+
x
5+
}
6+
}

0 commit comments

Comments
 (0)