Skip to content

Commit a235d54

Browse files
committed
Remove undefined from initialized+annotated parameter type
1 parent bb40819 commit a235d54

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/compiler/checker.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3286,6 +3286,16 @@ namespace ts {
32863286
return strictNullChecks && optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type;
32873287
}
32883288

3289+
/** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
3290+
function removeOptionalityFromAnnotation(annotatedType: Type, declaration: VariableLikeDeclaration): Type {
3291+
const annotationIncludesUndefined = strictNullChecks &&
3292+
declaration.kind === SyntaxKind.Parameter &&
3293+
declaration.initializer &&
3294+
getFalsyFlags(annotatedType) & TypeFlags.Undefined &&
3295+
!(getFalsyFlags(checkExpression(declaration.initializer)) & TypeFlags.Undefined);
3296+
return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType;
3297+
}
3298+
32893299
// Return the inferred type for a variable, parameter, or property declaration
32903300
function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, includeOptionality: boolean): Type {
32913301
if (declaration.flags & NodeFlags.JavaScriptFile) {
@@ -3319,7 +3329,8 @@ namespace ts {
33193329

33203330
// Use type from type annotation if one is present
33213331
if (declaration.type) {
3322-
return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
3332+
const declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration);
3333+
return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality);
33233334
}
33243335

33253336
if ((compilerOptions.noImplicitAny || declaration.flags & NodeFlags.JavaScriptFile) &&

0 commit comments

Comments
 (0)