Skip to content

Commit

Permalink
narrow from 'any' in most situations
Browse files Browse the repository at this point in the history
instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change.
  • Loading branch information
yortus committed Aug 13, 2016
1 parent 5bdde3b commit 0ad47db
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8548,10 +8548,6 @@ namespace ts {
}
return type;
}
// We never narrow type any in an instanceof guard
if (isTypeAny(type)) {
return type;
}

// Check that right operand is a function type with a prototype property
const rightType = checkExpression(expr.right);
Expand All @@ -8569,6 +8565,11 @@ namespace ts {
}
}

// Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
return type;
}

if (!targetType) {
// Target type is type of construct signature
let constructSignatures: Signature[];
Expand Down Expand Up @@ -8615,14 +8616,20 @@ namespace ts {
}

function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type {
if (type.flags & TypeFlags.Any || !hasMatchingArgument(callExpression, reference)) {
if (!hasMatchingArgument(callExpression, reference)) {
return type;
}
const signature = getResolvedSignature(callExpression);
const predicate = signature.typePredicate;
if (!predicate) {
return type;
}

// Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) {
return type;
}

if (isIdentifierTypePredicate(predicate)) {
const predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
Expand Down

0 comments on commit 0ad47db

Please sign in to comment.