Skip to content

Commit 65cea20

Browse files
committed
Use getTypeOfExpression when inferring variable type from initializer
1 parent 0afb84a commit 65cea20

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/compiler/checker.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16131,7 +16131,7 @@ namespace ts {
1613116131
}
1613216132

1613316133
function checkDeclarationInitializer(declaration: VariableLikeDeclaration) {
16134-
const type = checkExpressionCached(declaration.initializer);
16134+
const type = getTypeOfExpression(declaration.initializer, /*cache*/ true);
1613516135
return getCombinedNodeFlags(declaration) & NodeFlags.Const ||
1613616136
getCombinedModifierFlags(declaration) & ModifierFlags.Readonly && !isParameterPropertyDeclaration(declaration) ||
1613716137
isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type);
@@ -16204,10 +16204,12 @@ namespace ts {
1620416204

1620516205
// Returns the type of an expression. Unlike checkExpression, this function is simply concerned
1620616206
// with computing the type and may not fully check all contained sub-expressions for errors.
16207-
function getTypeOfExpression(node: Expression) {
16207+
// A cache argument of true indicates that if the function performs a full type check, it is ok
16208+
// to cache the result.
16209+
function getTypeOfExpression(node: Expression, cache?: boolean) {
1620816210
// Optimize for the common case of a call to a function with a single non-generic call
1620916211
// signature where we can just fetch the return type without checking the arguments.
16210-
if (node.kind === SyntaxKind.CallExpression && (<CallExpression>node).expression.kind !== SyntaxKind.SuperKeyword) {
16212+
if (node.kind === SyntaxKind.CallExpression && (<CallExpression>node).expression.kind !== SyntaxKind.SuperKeyword && !isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) {
1621116213
const funcType = checkNonNullExpression((<CallExpression>node).expression);
1621216214
const signature = getSingleCallSignature(funcType);
1621316215
if (signature && !signature.typeParameters) {
@@ -16217,7 +16219,7 @@ namespace ts {
1621716219
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
1621816220
// should have a parameter that indicates whether full error checking is required such that
1621916221
// we can perform the optimizations locally.
16220-
return checkExpression(node);
16222+
return cache ? checkExpressionCached(node) : checkExpression(node);
1622116223
}
1622216224

1622316225
// Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When

0 commit comments

Comments
 (0)