mirror of
https://github.com/microsoft/TypeScript.git
synced 2026-05-09 16:39:46 -05:00
@@ -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.
|
||||
|
||||
14
tests/baselines/reference/narrowUnknownByTypeofObject.js
Normal file
14
tests/baselines/reference/narrowUnknownByTypeofObject.js
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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
tests/baselines/reference/narrowUnknownByTypeofObject.types
Normal file
16
tests/baselines/reference/narrowUnknownByTypeofObject.types
Normal 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
|
||||
}
|
||||
}
|
||||
|
||||
6
tests/cases/compiler/narrowUnknownByTypeofObject.ts
Normal file
6
tests/cases/compiler/narrowUnknownByTypeofObject.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
// @strictNullChecks: true
|
||||
function foo(x: unknown) {
|
||||
if (typeof x === "object") {
|
||||
x
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user