Skip to content

Add undefined to default-initialised parameters #12033

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

Merged
merged 28 commits into from
Feb 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
995732f
Add undefined to default-valued parameters
sandersn Nov 3, 2016
286845c
Test adding undefined to default-valued parameters
sandersn Nov 3, 2016
00ff0e5
Do not add undefined to parameter properties
sandersn Nov 4, 2016
bb9b681
Merge branch 'master' into add-undefined-to-default-valued-parameters
sandersn Dec 8, 2016
96c14de
More tests:default-valued parameter+strictNullChecks
sandersn Dec 8, 2016
d62dd29
Merge branch 'master' into add-undefined-to-default-valued-parameters
sandersn Dec 13, 2016
caad486
More test cases and notes
sandersn Dec 13, 2016
bb6f3ad
Add parameter initialisers to control flow
sandersn Dec 14, 2016
f097eaf
More tests of parameter initialiser type
sandersn Dec 14, 2016
8b29e82
Merge branch 'master' into add-undefined-to-default-valued-parameters
sandersn Dec 16, 2016
6046318
Add `| undefined` in .d.ts for initialised params
sandersn Dec 16, 2016
739c083
More tests of initialised parameters adding undefined
sandersn Dec 16, 2016
cee708d
Remove undefined when checking patterns in function declarations
sandersn Dec 21, 2016
61c742a
Update tests
sandersn Dec 21, 2016
6543048
Change narrowing rules for parameter initialisers
sandersn Dec 21, 2016
3b1309d
Test parameter initialisation narrowing rules
sandersn Dec 21, 2016
e0bf73f
Remove old add-undefined code in getTypeOfParameter
sandersn Dec 21, 2016
156d5a9
Add `| undefined` to all optional properties too
sandersn Jan 5, 2017
8a9ee1a
Merge branch 'master' into add-undefined-to-default-valued-parameters
sandersn Jan 5, 2017
e96b17b
Merge branch 'master' into add-undefined-to-default-valued-parameters
sandersn Jan 26, 2017
01a9e4f
isOptionalParameter says unused IIFE arguments are optional
sandersn Jan 26, 2017
3c243db
Remove control flow-based undefined addition
sandersn Jan 27, 2017
bb40819
Update tests and baselines
sandersn Jan 27, 2017
a235d54
Remove undefined from initialized+annotated parameter type
sandersn Jan 30, 2017
7cf595a
Test removing undefined from initialized, annotated parameters
sandersn Jan 30, 2017
6f7c984
Address PR comments
sandersn Feb 1, 2017
6328e6c
Update baselines
sandersn Feb 1, 2017
c2cd4f6
Address PR comments and fix lint
sandersn Feb 13, 2017
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
39 changes: 35 additions & 4 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2694,7 +2694,11 @@ namespace ts {
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);

buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack);
let type = getTypeOfSymbol(p);
if (isRequiredInitializedParameter(parameterNode)) {
type = includeFalsyTypes(type, TypeFlags.Undefined);
}
buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack);
}

function buildBindingPatternDisplay(bindingPattern: BindingPattern, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) {
Expand Down Expand Up @@ -3275,6 +3279,16 @@ namespace ts {
return strictNullChecks && optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type;
}

/** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
function removeOptionalityFromAnnotation(annotatedType: Type, declaration: VariableLikeDeclaration): Type {
const annotationIncludesUndefined = strictNullChecks &&
declaration.kind === SyntaxKind.Parameter &&
declaration.initializer &&
getFalsyFlags(annotatedType) & TypeFlags.Undefined &&
!(getFalsyFlags(checkExpression(declaration.initializer)) & TypeFlags.Undefined);
return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType;
}

// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, includeOptionality: boolean): Type {
if (declaration.flags & NodeFlags.JavaScriptFile) {
Expand Down Expand Up @@ -3308,7 +3322,8 @@ namespace ts {

// Use type from type annotation if one is present
if (declaration.type) {
return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
const declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration);
return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality);
}

if ((compilerOptions.noImplicitAny || declaration.flags & NodeFlags.JavaScriptFile) &&
Expand Down Expand Up @@ -5133,6 +5148,12 @@ namespace ts {
Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
const iife = getImmediatelyInvokedFunctionExpression(node.parent);
if (iife) {
return !node.type &&
!node.dotDotDotToken &&
indexOf((node.parent as SignatureDeclaration).parameters, node) >= iife.arguments.length;
}

return false;
}
Expand Down Expand Up @@ -20526,6 +20547,13 @@ namespace ts {
return false;
}

function isRequiredInitializedParameter(parameter: ParameterDeclaration) {
return strictNullChecks &&
!isOptionalParameter(parameter) &&
parameter.initializer &&
!(getModifierFlags(parameter) & ModifierFlags.ParameterPropertyModifier);
}

function getNodeCheckFlags(node: Node): NodeCheckFlags {
node = getParseTreeNode(node);
return node ? getNodeLinks(node).flags : undefined;
Expand Down Expand Up @@ -20617,10 +20645,12 @@ namespace ts {
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) {
// Get type of the symbol if this is the valid symbol otherwise get type at location
const symbol = getSymbolOfNode(declaration);
const type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature))
let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature))
? getWidenedLiteralType(getTypeOfSymbol(symbol))
: unknownType;

if (flags & TypeFormatFlags.AddUndefined) {
type = includeFalsyTypes(type, TypeFlags.Undefined);
}
getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
}

Expand Down Expand Up @@ -20719,6 +20749,7 @@ namespace ts {
isTopLevelValueImportEqualsWithEntityName,
isDeclarationVisible,
isImplementationOfOverload,
isRequiredInitializedParameter,
writeTypeOfDeclaration,
writeReturnTypeOfSignatureDeclaration,
writeTypeOfExpression,
Expand Down
11 changes: 9 additions & 2 deletions src/compiler/declarationEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,13 +322,20 @@ namespace ts {
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, type: TypeNode, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) {
writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic;
write(": ");
if (type) {

// use the checker's type, not the declared type,
// for non-optional initialized parameters that aren't a parameter property
const shouldUseResolverType = declaration.kind === SyntaxKind.Parameter &&
resolver.isRequiredInitializedParameter(declaration as ParameterDeclaration);
if (type && !shouldUseResolverType) {
// Write the type
emitType(type);
}
else {
errorNameNode = declaration.name;
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue |
(shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0);
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
errorNameNode = undefined;
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2466,7 +2466,8 @@
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
InTypeAlias = 0x00000200, // Writing type in type alias declaration
UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters
}

export const enum SymbolFormatFlags {
Expand Down Expand Up @@ -2571,6 +2572,7 @@
isDeclarationVisible(node: Declaration): boolean;
collectLinkedAliases(node: Identifier): Node[];
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
Expand Down
8 changes: 4 additions & 4 deletions tests/baselines/reference/contextuallyTypedIife.types
Original file line number Diff line number Diff line change
Expand Up @@ -253,17 +253,17 @@ let eleven = (o => o.a(11))({ a: function(n) { return n; } });
// missing arguments
(function(x, undefined) { return x; })(42);
>(function(x, undefined) { return x; })(42) : number
>(function(x, undefined) { return x; }) : (x: number, undefined: any) => number
>function(x, undefined) { return x; } : (x: number, undefined: any) => number
>(function(x, undefined) { return x; }) : (x: number, undefined?: any) => number
>function(x, undefined) { return x; } : (x: number, undefined?: any) => number
>x : number
>undefined : any
>x : number
>42 : 42

((x, y, z) => 42)();
>((x, y, z) => 42)() : number
>((x, y, z) => 42) : (x: any, y: any, z: any) => number
>(x, y, z) => 42 : (x: any, y: any, z: any) => number
>((x, y, z) => 42) : (x?: any, y?: any, z?: any) => number
>(x, y, z) => 42 : (x?: any, y?: any, z?: any) => number
>x : any
>y : any
>z : any
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
//// [defaultParameterAddsUndefinedWithStrictNullChecks.ts]
function f(addUndefined1 = "J", addUndefined2?: number) {
return addUndefined1.length + (addUndefined2 || 0);
}
function g(addUndefined = "J", addDefined: number) {
return addUndefined.length + addDefined;
}
let total = f() + f('a', 1) + f('b') + f(undefined, 2);
total = g('c', 3) + g(undefined, 4);

function foo1(x: string = "string", b: number) {
x.length;
}

function foo2(x = "string", b: number) {
x.length; // ok, should be string
}

function foo3(x: string | undefined = "string", b: number) {
x.length; // ok, should be string
}

function foo4(x: string | undefined = undefined, b: number) {
x; // should be string | undefined
}



// .d.ts should have `string | undefined` for foo1, foo2, foo3 and foo4
foo1(undefined, 1);
foo2(undefined, 1);
foo3(undefined, 1);
foo4(undefined, 1);


function removeUndefinedButNotFalse(x = true) {
if (x === false) {
return x;
}
}

declare const cond: boolean;
function removeNothing(y = cond ? true : undefined) {
if (y !== undefined) {
if (y === false) {
return y;
}
}
return true;
}


//// [defaultParameterAddsUndefinedWithStrictNullChecks.js]
function f(addUndefined1, addUndefined2) {
if (addUndefined1 === void 0) { addUndefined1 = "J"; }
return addUndefined1.length + (addUndefined2 || 0);
}
function g(addUndefined, addDefined) {
if (addUndefined === void 0) { addUndefined = "J"; }
return addUndefined.length + addDefined;
}
var total = f() + f('a', 1) + f('b') + f(undefined, 2);
total = g('c', 3) + g(undefined, 4);
function foo1(x, b) {
if (x === void 0) { x = "string"; }
x.length;
}
function foo2(x, b) {
if (x === void 0) { x = "string"; }
x.length; // ok, should be string
}
function foo3(x, b) {
if (x === void 0) { x = "string"; }
x.length; // ok, should be string
}
function foo4(x, b) {
if (x === void 0) { x = undefined; }
x; // should be string | undefined
}
// .d.ts should have `string | undefined` for foo1, foo2, foo3 and foo4
foo1(undefined, 1);
foo2(undefined, 1);
foo3(undefined, 1);
foo4(undefined, 1);
function removeUndefinedButNotFalse(x) {
if (x === void 0) { x = true; }
if (x === false) {
return x;
}
}
function removeNothing(y) {
if (y === void 0) { y = cond ? true : undefined; }
if (y !== undefined) {
if (y === false) {
return y;
}
}
return true;
}


//// [defaultParameterAddsUndefinedWithStrictNullChecks.d.ts]
declare function f(addUndefined1?: string, addUndefined2?: number): number;
declare function g(addUndefined: string | undefined, addDefined: number): number;
declare let total: number;
declare function foo1(x: string | undefined, b: number): void;
declare function foo2(x: string | undefined, b: number): void;
declare function foo3(x: string | undefined, b: number): void;
declare function foo4(x: string | undefined, b: number): void;
declare function removeUndefinedButNotFalse(x?: boolean): false | undefined;
declare const cond: boolean;
declare function removeNothing(y?: boolean | undefined): boolean;
Loading