Narrowing unknown by typeof object to object | null

Fixes #26327
This commit is contained in:
Sheetal Nandi
2018-08-31 15:24:53 -07:00
parent cbdfc01e25
commit f1a179a314
5 changed files with 52 additions and 0 deletions

View File

@@ -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.

View File

@@ -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;
}
}

View File

@@ -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))
}
}

View File

@@ -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
}
}

View File

@@ -0,0 +1,6 @@
// @strictNullChecks: true
function foo(x: unknown) {
if (typeof x === "object") {
x
}
}