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

WIP: Member-type based type guards #6062

Closed
wants to merge 7 commits into from
Closed
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
2 changes: 1 addition & 1 deletion src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ namespace ts {
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
if (isNarrowingExpression(expr.left) && (expr.right.kind === SyntaxKind.NullKeyword || expr.right.kind === SyntaxKind.Identifier)) {
if (isNarrowingExpression(expr.left)) {
return true;
}
if (expr.left.kind === SyntaxKind.TypeOfExpression && isNarrowingExpression((<TypeOfExpression>expr.left).expression) && expr.right.kind === SyntaxKind.StringLiteral) {
Expand Down
99 changes: 98 additions & 1 deletion src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7698,6 +7698,103 @@ namespace ts {
return isMatchingReference(expr, reference) ? getTypeWithFacts(type, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy) : type;
}

function narrowTypeByValueExpression(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type {
assumeTrue = (expr.operatorToken.kind === SyntaxKind.EqualsEqualsEqualsToken || expr.operatorToken.kind === SyntaxKind.EqualsEqualsToken) ? assumeTrue : !assumeTrue;
let lhs = expr.left;
// selectors is the stack of property names used to select down into a type to get the member being narrowed
const selectors: string[] = [];
Copy link
Member

Choose a reason for hiding this comment

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

Document what a selector is.

while (lhs.kind !== SyntaxKind.Identifier) {
switch (lhs.kind) {
case SyntaxKind.ParenthesizedExpression:
lhs = (lhs as ParenthesizedExpression).expression;
break;
case SyntaxKind.PropertyAccessExpression:
const name = (lhs as PropertyAccessExpression).name.text;
// If a name doesn't resolve, bail
if (name === undefined) {
return type;
}
selectors.push(name);
lhs = (lhs as PropertyAccessExpression).expression;
break;
case SyntaxKind.Identifier:
break;
default:
// Unhandled control flow construct, don't narrow
return type;
}
}

if (!isMatchingReference(lhs, reference)) {
return type;
}
const rhsType = checkExpressionCached(expr.right);

if (assumeTrue) {
return narrowIntrospectively(type);
}
return type;

/**
* Descend into the type using the selectors we accumulated above and narrow any unions along the way
* If assumeTrue, we narrow by removing all types not compatible with the rhs type
* If not, we narrow only if the rhsType is a Value type (ie, StringLiteral) by removing all types compatible with that type (TODO)
*/
function narrowIntrospectively(type: Type) {
const propName = selectors.pop();
if (propName === undefined) {
// Selected all the way into the object, return the type for the property to be narrowed
if (isTypeSubtypeOf(rhsType, type)) {
return rhsType;
Copy link
Member

Choose a reason for hiding this comment

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

What if rhsType is any? Is everything now any?

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll use subtype.

}
else {
return type;
}
}
if (type.flags & TypeFlags.Union) {
const reducedUnion = getUnionType(
filter((type as UnionType).types, t => isMemberSubtype(t, rhsType, [...selectors, propName])),
/*noSubtypeReduction*/ true
);

if (reducedUnion !== emptyUnionType) {
return narrowBasedOnMatchingProperty(reducedUnion, propName);
}
else {
return type;
}
}

return narrowBasedOnMatchingProperty(type, propName);
}

function isMemberSubtype(type: Type, check: Type, selectors: string[]): boolean {
if (!selectors.length) {
return isTypeSubtypeOf(type, check);
}
const name = selectors.pop();
const childProp = getPropertyOfType(type, name);
const propType = childProp && getTypeOfSymbol(childProp);
return propType && isMemberSubtype(propType, check, selectors);
}

function narrowBasedOnMatchingProperty(type: Type, name: string): Type {
const childProp = getPropertyOfType(type, name);
const propType = childProp && getTypeOfSymbol(childProp);
const narrowedType = propType && narrowIntrospectively(propType);

if (narrowedType && !isTypeIdenticalTo(propType, narrowedType)) {
Copy link
Member

Choose a reason for hiding this comment

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

Add a newline above

const symbols = cloneSymbolTable(resolveStructuredTypeMembers(type as ObjectType).members);
const temp = createSymbol(childProp.flags, name);
getSymbolLinks(temp).type = narrowedType;
symbols[name] = temp;
return createAnonymousType(createSymbol(type.symbol.flags, type.symbol.name), symbols, getSignaturesOfType(type, SignatureKind.Call),
getSignaturesOfType(type, SignatureKind.Construct), getIndexInfoOfType(type, IndexKind.String), getIndexInfoOfType(type, IndexKind.Number));
}
return type;
}
}

function narrowTypeByBinaryExpression(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type {
switch (expr.operatorToken.kind) {
case SyntaxKind.EqualsToken:
Expand All @@ -7712,7 +7809,7 @@ namespace ts {
if (expr.left.kind === SyntaxKind.TypeOfExpression && expr.right.kind === SyntaxKind.StringLiteral) {
return narrowTypeByTypeof(type, expr, assumeTrue);
}
break;
return narrowTypeByValueExpression(type, expr, assumeTrue);
case SyntaxKind.InstanceOfKeyword:
return narrowTypeByInstanceof(type, expr, assumeTrue);
case SyntaxKind.CommaToken:
Expand Down
8 changes: 4 additions & 4 deletions tests/baselines/reference/equalityWithUnionTypes01.types
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,17 @@ else if (y == z || z == y) {
>y == z || z == y : boolean
>y == z : boolean
>y : I2
>z : I1
>z : I2
>z == y : boolean
>z : I1
>z : I2
>y : I2
}
else if (y != z || z != y) {
>y != z || z != y : boolean
>y != z : boolean
>y : I2
>z : I1
>z : I2
>z != y : boolean
>z : I1
>z : I2
>y : I2
}
107 changes: 107 additions & 0 deletions tests/baselines/reference/typeGuardByEqualityCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//// [typeGuardByEqualityCheck.ts]
interface Discriminator {
_discriminator: void;
}

interface FooDiscriminator extends Discriminator {
_foo: void;
}

interface BarDiscriminator extends Discriminator {
_bar: void;
}

interface BaseNode {
kind: Discriminator;
}

interface FooNode extends BaseNode {
kind: FooDiscriminator;
foo: string;
}

interface BarNode extends BaseNode {
kind: BarDiscriminator;
bar: string;
}

let a: FooDiscriminator;
let x: FooNode | BarNode;

if (x.kind === a) {
x.foo = "yay!";
}
else {
x; // Not narrowed at present
}

let z: {
value: string;
item: FooNode | BarNode;
}
if (z.item.kind === a) {
z.item.foo = "cool!";
z.value = "yes";
}

let foo: "foo";
let bar: "bar";
let foobar: "foobar";

interface Thing {
kind: string;
}
interface FooThing extends Thing {
kind: "foo";
foo: string;
}
interface BarThing extends Thing {
kind: "bar";
bar: string;
}
interface FooBarThing extends Thing {
kind: "foobar";
foo: string;
bar: string;
}

let gg: FooThing | BarThing | FooBarThing;
if (gg.kind === foobar) {
gg.bar = "bar";
gg.foo = "foo";
}
let holder = {
value: gg
};
if (holder.value.kind === foo) {
holder.value.foo = "foo";
}

//// [typeGuardByEqualityCheck.js]
var a;
var x;
if (x.kind === a) {
x.foo = "yay!";
}
else {
x; // Not narrowed at present
}
var z;
if (z.item.kind === a) {
z.item.foo = "cool!";
z.value = "yes";
}
var foo;
var bar;
var foobar;
var gg;
if (gg.kind === foobar) {
gg.bar = "bar";
gg.foo = "foo";
}
var holder = {
value: gg
};
if (holder.value.kind === foo) {
holder.value.foo = "foo";
}
Loading