Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
118 changes: 53 additions & 65 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7059,12 +7059,6 @@ namespace ts {
return strictNullChecks && optional ? getOptionalType(type) : type;
}

function isParameterOfContextuallyTypedFunction(node: Declaration) {
return node.kind === SyntaxKind.Parameter &&
(node.parent.kind === SyntaxKind.FunctionExpression || node.parent.kind === SyntaxKind.ArrowFunction) &&
!!getContextualType(<Expression>node.parent);
}

// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration: ParameterDeclaration | PropertyDeclaration | PropertySignature | VariableDeclaration | BindingElement, includeOptionality: boolean): Type | undefined {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
Expand Down Expand Up @@ -7136,7 +7130,7 @@ namespace ts {
}
}
// Use contextual parameter type if one is available
const type = declaration.symbol.escapedName === InternalSymbolName.This ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration, /*forCache*/ true);
const type = declaration.symbol.escapedName === InternalSymbolName.This ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
if (type) {
return addOptionality(type, isOptional);
}
Expand All @@ -7150,7 +7144,7 @@ namespace ts {

// Use the type of the initializer expression if one is present and the declaration is
// not a parameter of a contextually typed function
if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
if (declaration.initializer) {
const type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
return addOptionality(type, isOptional);
}
Expand All @@ -7163,7 +7157,7 @@ namespace ts {

// If the declaration specifies a binding pattern and is not a parameter of a contextually
// typed function, use the type implied by the binding pattern
if (isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
if (isBindingPattern(declaration.name)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}

Expand Down Expand Up @@ -21161,7 +21155,7 @@ namespace ts {
}

// Return contextual type of parameter or undefined if no contextual type is available
function getContextuallyTypedParameterType(parameter: ParameterDeclaration, forCache: boolean): Type | undefined {
function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type | undefined {
const func = parameter.parent;
if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
return undefined;
Expand All @@ -21182,21 +21176,8 @@ namespace ts {
links.resolvedSignature = cached;
return type;
}
let contextualSignature = getContextualSignature(func);
const contextualSignature = getContextualSignature(func);
if (contextualSignature) {
if (forCache) {
// Calling the below guarantees the types are primed and assigned in the same way
// as when the parameter is reached via `checkFunctionExpressionOrObjectLiteralMethod`.
// This should prevent any uninstantiated inference variables in the contextual signature
// from leaking, and should lock in cached parameter types via `assignContextualParameterTypes`
// which we will then immediately use the results of below.
contextuallyCheckFunctionExpressionOrObjectLiteralMethod(func);
const type = getTypeOfSymbol(getMergedSymbol(func.symbol));
if (isTypeAny(type)) {
return type;
}
contextualSignature = getSignaturesOfType(type, SignatureKind.Call)[0];
}
const index = func.parameters.indexOf(parameter) - (getThisParameter(func) ? 1 : 0);
return parameter.dotDotDotToken && lastOrUndefined(func.parameters) === parameter ?
getRestTypeAtPosition(contextualSignature, index) :
Expand All @@ -21211,7 +21192,7 @@ namespace ts {
}
switch (declaration.kind) {
case SyntaxKind.Parameter:
return getContextuallyTypedParameterType(declaration, /*forCache*/ false);
return getContextuallyTypedParameterType(declaration);
case SyntaxKind.BindingElement:
return getContextualTypeForBindingElement(declaration);
// By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
Expand Down Expand Up @@ -25994,23 +25975,47 @@ namespace ts {
if (!parameter) {
signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
}
assignTypeToParameterAndFixTypeParameters(signature.thisParameter!, getTypeOfSymbol(context.thisParameter));
assignParameterType(signature.thisParameter!, getTypeOfSymbol(context.thisParameter));
}
}
const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
for (let i = 0; i < len; i++) {
const parameter = signature.parameters[i];
if (!getEffectiveTypeAnnotationNode(<ParameterDeclaration>parameter.valueDeclaration)) {
const contextualParameterType = getTypeAtPosition(context, i);
assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType);
const contextualParameterType = tryGetTypeAtPosition(context, i);
assignParameterType(parameter, contextualParameterType);
}
}
if (signatureHasRestParameter(signature)) {
// parameter might be a transient symbol generated by use of `arguments` in the function body.
const parameter = last(signature.parameters);
if (isTransientSymbol(parameter) || !getEffectiveTypeAnnotationNode(<ParameterDeclaration>parameter.valueDeclaration)) {
const contextualParameterType = getRestTypeAtPosition(context, len);
assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType);
assignParameterType(parameter, contextualParameterType);
}
}
}

function assignNonContextualParameterTypes(signature: Signature) {
if (signature.thisParameter) {
assignParameterType(signature.thisParameter);
}
for (const parameter of signature.parameters) {
assignParameterType(parameter);
}
}

function assignParameterType(parameter: Symbol, type?: Type) {
const links = getSymbolLinks(parameter);
if (!links.type) {
const declaration = parameter.valueDeclaration as ParameterDeclaration;
links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
if (declaration.name.kind !== SyntaxKind.Identifier) {
// if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
if (links.type === unknownType) {
links.type = getTypeFromBindingPattern(declaration.name);
}
assignBindingElementTypes(declaration.name);
}
}
}
Expand All @@ -26030,21 +26035,6 @@ namespace ts {
}
}

function assignTypeToParameterAndFixTypeParameters(parameter: Symbol, contextualType: Type) {
const links = getSymbolLinks(parameter);
if (!links.type) {
links.type = contextualType;
const decl = parameter.valueDeclaration as ParameterDeclaration;
if (decl.name.kind !== SyntaxKind.Identifier) {
// if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
if (links.type === unknownType) {
links.type = getTypeFromBindingPattern(decl.name);
}
assignBindingElementTypes(decl.name);
}
}
}

function createPromiseType(promisedType: Type): Type {
// creates a `Promise<T>` type where `T` is the promisedType argument
const globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
Expand Down Expand Up @@ -26430,14 +26420,14 @@ namespace ts {
}
}

function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | MethodDeclaration, checkMode?: CheckMode): Type {
function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | ArrowFunction | MethodDeclaration, checkMode?: CheckMode): Type {
Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
checkNodeDeferred(node);

// The identityMapper object is used to indicate that function expressions are wildcards
if (checkMode && checkMode & CheckMode.SkipContextSensitive && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
if (!getEffectiveReturnTypeNode(node) && node.kind === SyntaxKind.ArrowFunction && node.parameters.length === 0) {
Comment thread
ahejlsberg marked this conversation as resolved.
Outdated
// Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
const contextualSignature = getContextualSignature(node);
if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
Expand All @@ -26461,14 +26451,9 @@ namespace ts {
checkGrammarForGenerator(node);
}

const type = getTypeOfSymbol(getMergedSymbol(node.symbol));
if (isTypeAny(type)) {
return type;
}

contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);

return type;
return getTypeOfSymbol(getSymbolOfNode(node));
Comment thread
weswigham marked this conversation as resolved.
}

function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | ArrowFunction | MethodDeclaration, checkMode?: CheckMode) {
Expand All @@ -26481,13 +26466,12 @@ namespace ts {
// already assigned contextual types.
if (!(links.flags & NodeCheckFlags.ContextChecked)) {
links.flags |= NodeCheckFlags.ContextChecked;
if (contextualSignature) {
const type = getTypeOfSymbol(getMergedSymbol(node.symbol));
if (isTypeAny(type)) {
return;
}
const signature = getSignaturesOfType(type, SignatureKind.Call)[0];
if (isContextSensitive(node)) {
const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), SignatureKind.Call));
Comment thread
weswigham marked this conversation as resolved.
if (!signature) {
return;
}
if (isContextSensitive(node)) {
if (contextualSignature) {
const inferenceContext = getInferenceContext(node);
if (checkMode && checkMode & CheckMode.Inferential) {
inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext!);
Expand All @@ -26496,11 +26480,15 @@ namespace ts {
instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
const returnType = getReturnTypeFromBody(node, checkMode);
if (!signature.resolvedReturnType) {
signature.resolvedReturnType = returnType;
}
else {
// Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
assignNonContextualParameterTypes(signature);
}
}
if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
const returnType = getReturnTypeFromBody(node, checkMode);
if (!signature.resolvedReturnType) {
signature.resolvedReturnType = returnType;
}
}
checkSignatureDeclaration(node);
Expand Down Expand Up @@ -28209,7 +28197,7 @@ namespace ts {
return checkClassExpression(<ClassExpression>node);
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return checkFunctionExpressionOrObjectLiteralMethod(<FunctionExpression>node, checkMode);
return checkFunctionExpressionOrObjectLiteralMethod(<FunctionExpression | ArrowFunction>node, checkMode);
case SyntaxKind.TypeOfExpression:
return checkTypeOfExpression(<TypeOfExpression>node);
case SyntaxKind.TypeAssertionExpression:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,54 @@
tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts(8,29): error TS7031: Binding element 'foo' implicitly has an 'any' type.
tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts(14,27): error TS7006: Parameter 'foo' implicitly has an 'any' type.
tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts(27,42): error TS7031: Binding element 'foo' implicitly has an 'any' type.
tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts(24,24): error TS7006: Parameter 'x' implicitly has an 'any' type.
tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts(40,5): error TS7006: Parameter 'x' implicitly has an 'any' type.


==== tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts (3 errors) ====
==== tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts (2 errors) ====
declare function id1<T>(input: T): T;
declare function id2<T extends (x: any) => any>(input: T): T;
declare function id3<T extends (x: { foo: any }) => any>(input: T): T;
declare function id4<T extends (x: { foo?: number }) => any>(input: T): T;
declare function id5<T extends (x?: number) => any>(input: T): T;

const f10 = function ({ foo = 42 }) { return foo };
const f11 = id1(function ({ foo = 42 }) { return foo }); // Implicit any error
~~~
!!! error TS7031: Binding element 'foo' implicitly has an 'any' type.
const f11 = id1(function ({ foo = 42 }) { return foo });
const f12 = id2(function ({ foo = 42 }) { return foo });
const f13 = id3(function ({ foo = 42 }) { return foo });
const f14 = id4(function ({ foo = 42 }) { return foo });

const f20 = function (foo = 42) { return foo };
const f21 = id1(function (foo = 42) { return foo }); // Implicit any error
~~~~~~~~
!!! error TS7006: Parameter 'foo' implicitly has an 'any' type.
const f21 = id1(function (foo = 42) { return foo });
const f22 = id2(function (foo = 42) { return foo });
const f25 = id5(function (foo = 42) { return foo });

const f1 = (x = 1) => 0; // number
const f2: any = (x = 1) => 0; // number
const f3: unknown = (x = 1) => 0; // number
const f4: Function = (x = 1) => 0; // number
const f5: (...args: any[]) => any = (x = 1) => 0; // any
const f6: () => any = (x = 1) => 0; // number
const f7: () => any = (x?) => 0; // Implicit any error
~~
!!! error TS7006: Parameter 'x' implicitly has an 'any' type.
const f8: () => any = (...x) => 0; // []

declare function g1<T>(x: T): T;
declare function g2<T extends any>(x: T): T;
declare function g3<T extends unknown>(x: T): T;
declare function g4<T extends Function>(x: T): T;
declare function g5<T extends (...args: any[]) => any>(x: T): T;
declare function g6<T extends () => any>(x: T): T;

g1((x = 1) => 0); // number
g2((x = 1) => 0); // number
g3((x = 1) => 0); // number
g4((x = 1) => 0); // number
g5((x = 1) => 0); // any
g6((x = 1) => 0); // number
g6((x?) => 0); // Implicit any error
~~
!!! error TS7006: Parameter 'x' implicitly has an 'any' type.
g6((...x) => 0); // []

// Repro from #28816

function id<T>(input: T): T { return input }
Expand All @@ -35,8 +59,35 @@ tests/cases/compiler/contextuallyTypedParametersWithInitializers.ts(27,42): erro

const newGetFoo = id(getFoo);
const newGetFoo2 = id(function getFoo ({ foo = 42 }) {
~~~
!!! error TS7031: Binding element 'foo' implicitly has an 'any' type.
return foo;
});

// Repro from comment in #30840

declare function memoize<F extends Function>(func: F): F;

function add(x: number, y = 0): number {
return x + y;
}
const memoizedAdd = memoize(add);

const add2 = (x: number, y = 0): number => x + y;
const memoizedAdd2 = memoize(add2);

const memoizedAdd3 = memoize((x: number, y = 0): number => x + y);

// Repro from #36052

declare function execute(script: string | Function): Promise<string>;

export function executeSomething() {
return execute((root: HTMLElement, debug = true) => {
if (debug) {
root.innerHTML = '';
}
});
}

const fz1 = (debug = true) => false;
const fz2: Function = (debug = true) => false;

Loading