Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Object.hasOwn narrowing #71

Draft
wants to merge 1 commit into
base: oss-hackathon-44253
Choose a base branch
from
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;
}