Skip to content

Commit 3835302

Browse files
committed
narrow from 'any' in most situations
instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change.
1 parent 10d1e02 commit 3835302

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/compiler/checker.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8548,10 +8548,6 @@ namespace ts {
85488548
}
85498549
return type;
85508550
}
8551-
// We never narrow type any in an instanceof guard
8552-
if (isTypeAny(type)) {
8553-
return type;
8554-
}
85558551

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

8568+
// Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
8569+
if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
8570+
return type;
8571+
}
8572+
85728573
if (!targetType) {
85738574
// Target type is type of construct signature
85748575
let constructSignatures: Signature[];
@@ -8615,14 +8616,20 @@ namespace ts {
86158616
}
86168617

86178618
function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type {
8618-
if (type.flags & TypeFlags.Any || !hasMatchingArgument(callExpression, reference)) {
8619+
if (!hasMatchingArgument(callExpression, reference)) {
86198620
return type;
86208621
}
86218622
const signature = getResolvedSignature(callExpression);
86228623
const predicate = signature.typePredicate;
86238624
if (!predicate) {
86248625
return type;
86258626
}
8627+
8628+
// Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
8629+
if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) {
8630+
return type;
8631+
}
8632+
86268633
if (isIdentifierTypePredicate(predicate)) {
86278634
const predicateArgument = callExpression.arguments[predicate.parameterIndex];
86288635
if (predicateArgument) {

0 commit comments

Comments
 (0)