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

add type guard of constructor #23622

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
32 changes: 30 additions & 2 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13474,6 +13474,18 @@ namespace ts {
if (containsMatchingReferenceDiscriminant(reference, left) || containsMatchingReferenceDiscriminant(reference, right)) {
return declaredType;
}
if (isPropertyAccessExpression(left) && idText(left.name) === "constructor") {
return narrowTypeByConstructor(type, expr.right, operator, assumeTrue);
}
if (isPropertyAccessExpression(right) && idText(right.name) === "constructor") {
return narrowTypeByConstructor(type, expr.left, operator, assumeTrue);
}
if (isElementAccessExpression(left) && isStringLiteralLike(left.argumentExpression) && left.argumentExpression.text === "constructor") {
return narrowTypeByConstructor(type, expr.right, operator, assumeTrue);
}
if (isElementAccessExpression(right) && isStringLiteralLike(right.argumentExpression) && right.argumentExpression.text === "constructor") {
return narrowTypeByConstructor(type, expr.left, operator, assumeTrue);
}
break;
case SyntaxKind.InstanceOfKeyword:
return narrowTypeByInstanceof(type, expr, assumeTrue);
Expand All @@ -13493,7 +13505,7 @@ namespace ts {
if (type.flags & TypeFlags.Any) {
return type;
}
if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) {
if (isExclamationEqualsOrExclamationEqualsEqualsKind(operator)) {
assumeTrue = !assumeTrue;
}
const valueType = getTypeOfExpression(value);
Expand Down Expand Up @@ -13523,6 +13535,22 @@ namespace ts {
return type;
}

function narrowTypeByConstructor(type: Type, expr: Expression, operator: SyntaxKind, assumeTrue: boolean): Type {
if (!assumeTrue || isExclamationEqualsOrExclamationEqualsEqualsKind(operator)) return type;

const rightType = getTypeOfExpression(expr);
if (!isTypeSubtypeOf(rightType, globalFunctionType)) return type;

const prototypeProperty = getPropertyOfType(rightType, "prototype" as __String);
if (!prototypeProperty) return type;

const prototypePropertyType = getTypeOfSymbol(prototypeProperty);
const targetType = !isTypeAny(prototypePropertyType) ? prototypePropertyType : undefined;
if (!targetType || isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) return type;

return getNarrowedType(type, targetType, assumeTrue, areTypesComparable);
Copy link
Member

Choose a reason for hiding this comment

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

I don't think you want areTypesComparable because this will work for types which don't explicitly derive from a given constructor.

I think you potentially want a helper function that uses isTypeDerivedFrom on the wrapper object type for any primitive types.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

will work for types which don't explicitly derive from a given constructor

could you give some example? 😢

}

function narrowTypeByTypeof(type: Type, typeOfExpr: TypeOfExpression, operator: SyntaxKind, literal: LiteralExpression, assumeTrue: boolean): Type {
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
const target = getReferenceCandidate(typeOfExpr.expression);
Expand All @@ -13534,7 +13562,7 @@ namespace ts {
}
return type;
}
if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) {
if (isExclamationEqualsOrExclamationEqualsEqualsKind(operator)) {
assumeTrue = !assumeTrue;
}
if (assumeTrue && !(type.flags & TypeFlags.Union)) {
Expand Down
5 changes: 5 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6335,4 +6335,9 @@ namespace ts {
export function isNamedImportsOrExports(node: Node): node is NamedImportsOrExports {
return node.kind === SyntaxKind.NamedImports || node.kind === SyntaxKind.NamedExports;
}

/** @internal */
export function isExclamationEqualsOrExclamationEqualsEqualsKind(kind: SyntaxKind): boolean {
Copy link
Member

Choose a reason for hiding this comment

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

Maybe isNegatedEqualityToken? *shrug*

return kind === SyntaxKind.ExclamationEqualsToken || kind === SyntaxKind.ExclamationEqualsEqualsToken;
}
}
105 changes: 105 additions & 0 deletions tests/baselines/reference/typeGuardConstructor.errors.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
tests/cases/conformance/expressions/typeGuards/typeGuardConstructor.ts(45,11): error TS2339: Property 'p2' does not exist on type 'C1 | C2'.
Property 'p2' does not exist on type 'C1'.
tests/cases/conformance/expressions/typeGuards/typeGuardConstructor.ts(49,11): error TS2339: Property 'p2' does not exist on type 'C1 | C2'.
Property 'p2' does not exist on type 'C1'.
tests/cases/conformance/expressions/typeGuards/typeGuardConstructor.ts(52,11): error TS2339: Property 'p1' does not exist on type 'C1 | C2'.
Property 'p1' does not exist on type 'C2'.
tests/cases/conformance/expressions/typeGuards/typeGuardConstructor.ts(63,11): error TS2339: Property 'p4' does not exist on type 'C1 | C2 | C3'.
Property 'p4' does not exist on type 'C1'.


==== tests/cases/conformance/expressions/typeGuards/typeGuardConstructor.ts (4 errors) ====
class C1 {
p1: string;
}
class C2 {
p2: number;
}
class D1 extends C1 {
p3: number;
}
class C3 {
p4: number;
}
class D2 extends D1 {
p5: number
}

var a: C1;
if (a.constructor === D1) {
a.p3;
}
if (a.constructor == D1) {
a.p3;
}
if (D1 === a.constructor) {
a.p3;
}
if (a["constructor"] === D1) {
a.p3;
}
if (D1 === a["constructor"]) {
a.p3;
}

var b: C1;
if (b.constructor === D2) {
b.p3;
b.p5;
}

var ctor3: C1 | C2;
if (ctor3.constructor === C1) {
ctor3.p1; // C1
}
else {
ctor3.p2; // C2
~~
!!! error TS2339: Property 'p2' does not exist on type 'C1 | C2'.
!!! error TS2339: Property 'p2' does not exist on type 'C1'.
}

if (ctor3.constructor !== C1) {
ctor3.p2; // C1
~~
!!! error TS2339: Property 'p2' does not exist on type 'C1 | C2'.
!!! error TS2339: Property 'p2' does not exist on type 'C1'.
}
else {
ctor3.p1; // C2
~~
!!! error TS2339: Property 'p1' does not exist on type 'C1 | C2'.
!!! error TS2339: Property 'p1' does not exist on type 'C2'.
}

var ctor4: C1 | C2 | C3;
if (ctor4.constructor === C1) {
ctor4.p1; // C1
}
else if (ctor4.constructor === C2) {
ctor4.p2; // C2
}
else {
ctor4.p4; // C3
~~
!!! error TS2339: Property 'p4' does not exist on type 'C1 | C2 | C3'.
!!! error TS2339: Property 'p4' does not exist on type 'C1'.
}

var x: number | "hello" | "world" | true | 1[] | undefined;
if (x.constructor === String) {
x.length;
}

if (x.constructor === Number) {
x.toFixed();
}

if (x.constructor === Boolean) {
const b = x;
}

if(x.constructor === Array) {
const c = x[0];
}

181 changes: 181 additions & 0 deletions tests/baselines/reference/typeGuardConstructor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
//// [typeGuardConstructor.ts]
class C1 {
p1: string;
}
class C2 {
p2: number;
}
class D1 extends C1 {
p3: number;
}
class C3 {
p4: number;
}
class D2 extends D1 {
p5: number
}

var a: C1;
if (a.constructor === D1) {
a.p3;
}
if (a.constructor == D1) {
a.p3;
}
if (D1 === a.constructor) {
a.p3;
}
if (a["constructor"] === D1) {
a.p3;
}
if (D1 === a["constructor"]) {
a.p3;
}

var b: C1;
if (b.constructor === D2) {
b.p3;
b.p5;
}

var ctor3: C1 | C2;
if (ctor3.constructor === C1) {
ctor3.p1; // C1
}
else {
ctor3.p2; // C2
}

if (ctor3.constructor !== C1) {
ctor3.p2; // C1
}
else {
ctor3.p1; // C2
}

var ctor4: C1 | C2 | C3;
if (ctor4.constructor === C1) {
ctor4.p1; // C1
}
else if (ctor4.constructor === C2) {
ctor4.p2; // C2
}
else {
ctor4.p4; // C3
}

var x: number | "hello" | "world" | true | 1[] | undefined;
if (x.constructor === String) {
x.length;
}

if (x.constructor === Number) {
x.toFixed();
}

if (x.constructor === Boolean) {
const b = x;
}

if(x.constructor === Array) {
const c = x[0];
}


//// [typeGuardConstructor.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var C1 = /** @class */ (function () {
function C1() {
}
return C1;
}());
var C2 = /** @class */ (function () {
function C2() {
}
return C2;
}());
var D1 = /** @class */ (function (_super) {
__extends(D1, _super);
function D1() {
return _super !== null && _super.apply(this, arguments) || this;
}
return D1;
}(C1));
var C3 = /** @class */ (function () {
function C3() {
}
return C3;
}());
var D2 = /** @class */ (function (_super) {
__extends(D2, _super);
function D2() {
return _super !== null && _super.apply(this, arguments) || this;
}
return D2;
}(D1));
var a;
if (a.constructor === D1) {
a.p3;
}
if (a.constructor == D1) {
a.p3;
}
if (D1 === a.constructor) {
a.p3;
}
if (a["constructor"] === D1) {
a.p3;
}
if (D1 === a["constructor"]) {
a.p3;
}
var b;
if (b.constructor === D2) {
b.p3;
b.p5;
}
var ctor3;
if (ctor3.constructor === C1) {
ctor3.p1; // C1
}
else {
ctor3.p2; // C2
}
if (ctor3.constructor !== C1) {
ctor3.p2; // C1
}
else {
ctor3.p1; // C2
}
var ctor4;
if (ctor4.constructor === C1) {
ctor4.p1; // C1
}
else if (ctor4.constructor === C2) {
ctor4.p2; // C2
}
else {
ctor4.p4; // C3
}
var x;
if (x.constructor === String) {
x.length;
}
if (x.constructor === Number) {
x.toFixed();
}
if (x.constructor === Boolean) {
var b_1 = x;
}
if (x.constructor === Array) {
var c = x[0];
}
Loading