Skip to content
Draft
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
8 changes: 8 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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])) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A downside to special casing the exact names here is that it would break for cases where the function is assigned to a different name:

const hasProp = Object.hasOwn;

if (hasProp(o, 'test')) ...

I think instead of adding this logic within the compiler itself, we might be able to do it by updating the .d.ts definitions that are packaged with tsc. Something like:

interface ObjectConstructor {
    hasOwn<T, P extends string>(o: T, p: P): o is Extract<T, { [p in P]: unknown }>; 
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, it seems like we have the necessary building blocks to express this already.

return narrowByInKeyword(type, callExpression.arguments[1].text as __String, assumeTrue);
}
}
return type;
}

Expand Down
6 changes: 6 additions & 0 deletions tests/cases/compiler/objectHasOwnNarrowingSimpleUnion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// @target: es2022

declare const abcd: { a: string, b: number } | { c: number, d: string };
if (Object.hasOwn(abcd, "a")) {
abcd.b;
}