Skip to content

Contextually type unions of differing signatures, rather than giving up #17819

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

Closed
Show file tree
Hide file tree
Changes from all 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
169 changes: 134 additions & 35 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7060,8 +7060,8 @@ namespace ts {
return signature.resolvedReturnType;
}

function isResolvingReturnTypeOfSignature(signature: Signature) {
return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, TypeSystemPropertyName.ResolvedReturnType) >= 0;
function isResolvingReturnTypeOfSignature(signature: Signature): boolean {
return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, TypeSystemPropertyName.ResolvedReturnType) >= 0 || (signature.unionSignatures && some(signature.unionSignatures, s => isResolvingReturnTypeOfSignature(s)));
}

function getRestTypeOfSignature(signature: Signature): Type {
Expand Down Expand Up @@ -14339,18 +14339,11 @@ namespace ts {

// If the given type is an object or union type with a single signature, and if that signature has at
// least as many parameters as the given function, return the signature. Otherwise return undefined.
function getContextualCallSignature(type: Type, node: FunctionExpression | ArrowFunction | MethodDeclaration): Signature {
const signatures = getSignaturesOfStructuredType(type, SignatureKind.Call);
if (signatures.length === 1) {
const signature = signatures[0];
if (!isAritySmaller(signature, node)) {
return signature;
}
}
function getContextualCallSignatures(type: Type, node: FunctionExpression | ArrowFunction | MethodDeclaration): Signature[] {
return filter(getSignaturesOfStructuredType(type, SignatureKind.Call), s => !isAritySmaller(s, node));
}

/** If the contextual signature has fewer parameters than the function expression, do not use it */
function isAritySmaller(signature: Signature, target: FunctionExpression | ArrowFunction | MethodDeclaration) {
function getMinimumArityOf(target: SignatureDeclaration) {
let targetParameterCount = 0;
for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
const param = target.parameters[targetParameterCount];
Expand All @@ -14361,6 +14354,12 @@ namespace ts {
if (target.parameters.length && parameterIsThisKeyword(target.parameters[0])) {
targetParameterCount--;
}
return targetParameterCount;
}

/** If the contextual signature has fewer parameters than the function expression, do not use it */
function isAritySmaller(signature: Signature, target: FunctionExpression | ArrowFunction | MethodDeclaration) {
const targetParameterCount = getMinimumArityOf(target);
const sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length;
return sourceLength < targetParameterCount;
}
Expand All @@ -14382,6 +14381,96 @@ namespace ts {
getApparentTypeOfContextualType(node);
}

function combineSignatures(signatureList: Signature[], declaration: SignatureDeclaration): Signature {
// Produce a synthetic signature whose arguments are a union of the parameters of the inferred signatures and whose return type is an intersection
const parameters: Symbol[] = [];
const restTypes: TypeSet = [];
let thisTypes: Type[];
let hasLiteralTypes = false;
let hasRestParameter = false;
const oldTypeParameters = flatMap(signatureList, s => s.typeParameters);
const newTypeParameters = map(oldTypeParameters, cloneTypeParameter);
const mapper = createTypeMapper(oldTypeParameters, newTypeParameters);

// First, for every parameter the user has written, lookup a corresponding union of types from the associated signatures
if (declaration.parameters && declaration.parameters.length) {
for (let i = 0; i < declaration.parameters.length ; i++) {
const param = declaration.parameters[i];
// We do this so the name is reasonable for users; however it is very rare for this symbol name to appear anywhere user-facing, as the result signature is used only for contextual typing
const canUseUserSuppliedName = isIdentifier(param.name);
const paramName = canUseUserSuppliedName ? (param.name as Identifier).escapedText : escapeLeadingUnderscores("arg");
const paramSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, paramName);
const parameterTypes: TypeSet = [];
if (param.dotDotDotToken) {
hasRestParameter = true;
for (const signature of signatureList) {
for (let j = i; j < signature.parameters.length; j++) {
handleAddingTypesForParameter(signature, j, parameterTypes);
}
}
paramSymbol.type = createArrayType(getUnionType(restTypes ? parameterTypes.concat(restTypes) : parameterTypes));
parameters.push(paramSymbol);
break;
}
else {
for (const signature of signatureList) {
handleAddingTypesForParameter(signature, i, parameterTypes);
}
paramSymbol.type = getUnionType(restTypes.length ? parameterTypes.concat(restTypes) : parameterTypes);
parameters.push(paramSymbol);
}
}
}

// Then, collect aggrgate statistics about all signatures to determine the characteristics of the resulting signature
for (const signature of signatureList) {
if (signature.hasLiteralTypes) {
hasLiteralTypes = true;
}
if (signature.thisParameter) {
(thisTypes || (thisTypes = [])).push(instantiateType(getTypeOfSymbol(signature.thisParameter), mapper));
}
else if (compilerOptions.noImplicitThis) {
(thisTypes || (thisTypes = [])).push(undefinedType);
}
}

let thisParameterSymbol: TransientSymbol;
if (thisTypes && thisTypes.length) {
thisParameterSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "this" as __String);
thisParameterSymbol.type = getUnionType(thisTypes);
}

return createSignature(
declaration,
newTypeParameters,
thisParameterSymbol,
parameters,
instantiateType(getIntersectionType(map(signatureList, getReturnTypeOfSignature)), mapper),
/*typePredicate*/ undefined,
getMinimumArityOf(declaration),
hasRestParameter,
hasLiteralTypes
);

function handleAddingTypesForParameter(signature: Signature, i: number, parameterTypes: TypeSet) {
const sigParam = signature.parameters[i];
if (sigParam && !(signature.hasRestParameter && i === (signature.parameters.length - 1))) {
addTypeToUnion(parameterTypes, instantiateType(getTypeOfSymbol(sigParam), mapper));
return;
}
if (signature.hasRestParameter) {
const innerType = getRestTypeOfSignature(signature) || anyType;
const newInnerType = instantiateType(innerType, mapper);
addTypeToUnion(parameterTypes, newInnerType);
addTypeToUnion(restTypes, newInnerType);
}
if (compilerOptions.strictNullChecks) {
addTypeToUnion(parameterTypes, undefinedType);
}
}
}

// Return the contextual signature for a given expression node. A contextual type provides a
// contextual signature if it has a single call signature and if that call signature is non-generic.
// If the contextual type is a union type, get the signature from each type possible and if they are
Expand All @@ -14393,35 +14482,45 @@ namespace ts {
if (!type) {
return undefined;
}
let signatureList: Signature[];
if (!(type.flags & TypeFlags.Union)) {
return getContextualCallSignature(type, node);
signatureList = getContextualCallSignatures(type, node);
}
let signatureList: Signature[];
const types = (<UnionType>type).types;
for (const current of types) {
const signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
// This signature will contribute to contextual union signature
signatureList = [signature];
}
else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
// Signatures aren't identical, do not use
return undefined;
}
else {
// Use this signature for contextual union signature
signatureList.push(signature);
else {
const types = (<UnionType>type).types;
for (const current of types) {
const signatures = getContextualCallSignatures(current, node);
if (signatures && signatures.length) {
if (!signatureList) {
signatureList = signatures;
}
else {
signatureList = signatureList.concat(signatures);
}
}
}
}

// Result is union of signatures collected (return type is union of return types of this signature set)
let result: Signature;
if (signatureList) {
result = cloneSignature(signatureList[0]);
result.unionSignatures = signatureList;
if (!(signatureList && signatureList.length)) {
return undefined;
}

if (signatureList.length === 1) {
return signatureList[0];
}

for (const signature of signatureList) {
if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
// Signatures not simply identical, combine them
return combineSignatures(signatureList, node);
}
}

// Result is union of signatures collected (return type is union of return types of this signature set)
const result = cloneSignature(signatureList[0]);
// Clear resolved return type we possibly got from cloneSignature
result.resolvedReturnType = undefined;
result.unionSignatures = signatureList;
return result;
}

Expand Down Expand Up @@ -18025,7 +18124,7 @@ namespace ts {

if (isUnitType(type)) {
let contextualType = !contextualSignature ? undefined :
contextualSignature === getSignatureFromDeclaration(func) ? type :
contextualSignature === getSignatureFromDeclaration(func) || contextualSignature.unionSignatures && some(contextualSignature.unionSignatures, s => s === getSignatureFromDeclaration(func)) ? type :
getReturnTypeOfSignature(contextualSignature);
if (contextualType) {
switch (functionFlags & FunctionFlags.AsyncGenerator) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,17 @@ var x3: IWithCallSignatures | IWithCallSignatures3 = a => /*here a should be any
>IWithCallSignatures : Symbol(IWithCallSignatures, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 9, 1))
>IWithCallSignatures3 : Symbol(IWithCallSignatures3, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 15, 1))
>a : Symbol(a, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 32, 52))
>a.toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 32, 52))
>toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))

// With call signature count mismatch
var x4: IWithCallSignatures | IWithCallSignatures4 = a => /*here a should be any*/ a.toString();
>x4 : Symbol(x4, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 35, 3))
>IWithCallSignatures : Symbol(IWithCallSignatures, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 9, 1))
>IWithCallSignatures4 : Symbol(IWithCallSignatures4, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 18, 1))
>a : Symbol(a, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 35, 52))
>a.toString : Symbol(Number.toString, Decl(lib.d.ts, --, --))
>a.toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 35, 52))
>toString : Symbol(Number.toString, Decl(lib.d.ts, --, --))
>toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))

Original file line number Diff line number Diff line change
Expand Up @@ -78,22 +78,22 @@ var x3: IWithCallSignatures | IWithCallSignatures3 = a => /*here a should be any
>x3 : IWithCallSignatures | IWithCallSignatures3
>IWithCallSignatures : IWithCallSignatures
>IWithCallSignatures3 : IWithCallSignatures3
>a => /*here a should be any*/ a.toString() : (a: any) => any
>a : any
>a.toString() : any
>a.toString : any
>a : any
>toString : any
>a => /*here a should be any*/ a.toString() : (a: string | number) => string
>a : string | number
>a.toString() : string
>a.toString : ((radix?: number) => string) | (() => string)
>a : string | number
>toString : ((radix?: number) => string) | (() => string)

// With call signature count mismatch
var x4: IWithCallSignatures | IWithCallSignatures4 = a => /*here a should be any*/ a.toString();
>x4 : IWithCallSignatures | IWithCallSignatures4
>IWithCallSignatures : IWithCallSignatures
>IWithCallSignatures4 : IWithCallSignatures4
>a => /*here a should be any*/ a.toString() : (a: number) => string
>a : number
>a => /*here a should be any*/ a.toString() : (a: string | number) => string
>a : string | number
>a.toString() : string
>a.toString : (radix?: number) => string
>a : number
>toString : (radix?: number) => string
>a.toString : ((radix?: number) => string) | (() => string)
>a : string | number
>toString : ((radix?: number) => string) | (() => string)

9 changes: 8 additions & 1 deletion tests/baselines/reference/contextualTyping.errors.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
tests/cases/compiler/contextualTyping.ts(36,5): error TS2322: Type '(n: string | number) => string | number' is not assignable to type '{ (n: number): number; (s1: string): number; }'.
Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/compiler/contextualTyping.ts(189,18): error TS2384: Overload signatures must all be ambient or non-ambient.
tests/cases/compiler/contextualTyping.ts(197,15): error TS2300: Duplicate identifier 'Point'.
tests/cases/compiler/contextualTyping.ts(207,10): error TS2300: Duplicate identifier 'Point'.
tests/cases/compiler/contextualTyping.ts(230,5): error TS2322: Type '{}' is not assignable to type 'B'.
Property 'x' is missing in type '{}'.


==== tests/cases/compiler/contextualTyping.ts (4 errors) ====
==== tests/cases/compiler/contextualTyping.ts (5 errors) ====
// DEFAULT INTERFACES
interface IFoo {
n: number;
Expand Down Expand Up @@ -42,6 +45,10 @@ tests/cases/compiler/contextualTyping.ts(230,5): error TS2322: Type '{}' is not
var c3t5: (n: number) => IFoo = function(n) { return <IFoo>({}) };
var c3t6: (n: number, s: string) => IFoo = function(n, s) { return <IFoo>({}) };
var c3t7: {
~~~~
!!! error TS2322: Type '(n: string | number) => string | number' is not assignable to type '{ (n: number): number; (s1: string): number; }'.
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
(n: number): number;
(s1: string): number;
} = function(n) { return n; };
Expand Down
6 changes: 3 additions & 3 deletions tests/baselines/reference/contextualTyping.types
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,9 @@ var c3t7: {
>s1 : string

} = function(n) { return n; };
>function(n) { return n; } : (n: any) => any
>n : any
>n : any
>function(n) { return n; } : (n: string | number) => string | number
>n : string | number
>n : string | number

var c3t8: (n: number, s: string) => number = function(n) { return n; };
>c3t8 : (n: number, s: string) => number
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ var foo: Foo;
>Foo : Foo

foo.getFoo = bar => { };
>foo.getFoo = bar => { } : (bar: any) => void
>foo.getFoo = bar => { } : (bar: string | number) => void
>foo.getFoo : { (n: number): void; (s: string): void; }
>foo : Foo
>getFoo : { (n: number): void; (s: string): void; }
>bar => { } : (bar: any) => void
>bar : any
>bar => { } : (bar: string | number) => void
>bar : string | number

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
tests/cases/compiler/contextualTypingOfLambdaWithMultipleSignatures2.ts(6,23): error TS2339: Property 'asdf' does not exist on type 'string | number'.
Property 'asdf' does not exist on type 'string'.


==== tests/cases/compiler/contextualTypingOfLambdaWithMultipleSignatures2.ts (1 errors) ====
var f: {
(x: string): string;
(x: number): string
};

f = (a) => { return a.asdf }
~~~~
!!! error TS2339: Property 'asdf' does not exist on type 'string | number'.
!!! error TS2339: Property 'asdf' does not exist on type 'string'.
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ var f: {
};

f = (a) => { return a.asdf }
>f = (a) => { return a.asdf } : (a: any) => any
>f = (a) => { return a.asdf } : (a: string | number) => any
>f : { (x: string): string; (x: number): string; }
>(a) => { return a.asdf } : (a: any) => any
>a : any
>(a) => { return a.asdf } : (a: string | number) => any
>a : string | number
>a.asdf : any
>a : any
>a : string | number
>asdf : any

Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ var f2: {
};

f2 = (x, y) => { return x }
>f2 = (x, y) => { return x } : (x: any, y: any) => any
>f2 = (x, y) => { return x } : <T, U>(x: string | T, y: number | U) => string | T
>f2 : { (x: string, y: number): string; <T, U>(x: T, y: U): T; }
>(x, y) => { return x } : (x: any, y: any) => any
>x : any
>y : any
>x : any
>(x, y) => { return x } : <T, U>(x: string | T, y: number | U) => string | T
>x : string | T
>y : number | U
>x : string | T

var f3: {
>f3 : { <T, U>(x: T, y: U): T; (x: string, y: number): string; }
Expand All @@ -46,10 +46,10 @@ var f3: {
};

f3 = (x, y) => { return x }
>f3 = (x, y) => { return x } : (x: any, y: any) => any
>f3 = (x, y) => { return x } : <T, U>(x: string | T, y: number | U) => string | T
>f3 : { <T, U>(x: T, y: U): T; (x: string, y: number): string; }
>(x, y) => { return x } : (x: any, y: any) => any
>x : any
>y : any
>x : any
>(x, y) => { return x } : <T, U>(x: string | T, y: number | U) => string | T
>x : string | T
>y : number | U
>x : string | T

Loading