From 55d6e330a1676c01f4ce15434162c1d1aea6060f Mon Sep 17 00:00:00 2001 From: pgorostiagab Date: Thu, 16 Jun 2022 13:16:11 +0100 Subject: [PATCH] Initial hacky implementation using InKeyword narrowing and simple test --- src/compiler/checker.ts | 8 ++++++++ tests/cases/compiler/objectHasOwnNarrowingSimpleUnion.ts | 6 ++++++ 2 files changed, 14 insertions(+) create mode 100644 tests/cases/compiler/objectHasOwnNarrowingSimpleUnion.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9e56c58411930..d91e4a94bb766 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -25289,6 +25289,7 @@ namespace ts { } function narrowTypeByCallExpression(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type { + debugger; if (hasMatchingArgument(callExpression, reference)) { const signature = assumeTrue || !isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined; const predicate = signature && getTypePredicateOfSignature(signature); @@ -25306,6 +25307,13 @@ namespace ts { } } } + + if (isPropertyAccessExpression(callExpression.expression)) { + const callAccess = callExpression.expression; + if (isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwn" && callExpression.arguments.length === 2 && isStringLiteralLike(callExpression.arguments[1])) { + return narrowByInKeyword(type, callExpression.arguments[1].text as __String, assumeTrue); + } + } return type; } diff --git a/tests/cases/compiler/objectHasOwnNarrowingSimpleUnion.ts b/tests/cases/compiler/objectHasOwnNarrowingSimpleUnion.ts new file mode 100644 index 0000000000000..6a5a4acecc1ff --- /dev/null +++ b/tests/cases/compiler/objectHasOwnNarrowingSimpleUnion.ts @@ -0,0 +1,6 @@ +// @target: es2022 + +declare const abcd: { a: string, b: number } | { c: number, d: string }; +if (Object.hasOwn(abcd, "a")) { + abcd.b; +}