Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
3451575
Infer type parameters from indexes on those parameters
weswigham Nov 18, 2017
f5b208c
Greatly simplify partial inference type instantiation through use of …
weswigham Nov 22, 2017
ba064ac
Add many more tests showing current behaviors
weswigham Nov 22, 2017
93afc10
Discriminate partial inferences if not complete enough to satisfy con…
weswigham Dec 1, 2017
49e1961
Move case to prefered location
weswigham Dec 21, 2017
96772e5
Small refactor to reduce how many comparisons are performed
weswigham Dec 21, 2017
2e0c635
Infer reverse mapped types based on inferences made for its concrete …
Andarist Feb 28, 2023
7b8cf10
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Apr 17, 2023
e7e4e70
Merge remote-tracking branch 'weswigham/index-combined-inferences' in…
Andarist Apr 17, 2023
d0e8b8b
update baselines, note: some are broken
Andarist Apr 17, 2023
e5d0ea8
use new `inference.indexes` in reverse mapped type inference
Andarist Apr 17, 2023
b0b2fcb
update reverse mapped baseline
Andarist Apr 18, 2023
7fe118a
Call `getActualTypeVariable` appropriately to fix inference for a tup…
Andarist Apr 18, 2023
50e6a0c
Avoid inferring an index under `InferencePriority.NakedTypeVariable`
Andarist Apr 18, 2023
4febb9c
always discard aggregate inference that is not assignable to the cons…
Andarist Apr 19, 2023
c2d4b0f
bring back the union discriminating logic
Andarist Apr 19, 2023
11b02d0
fixed incorrect indexed access in tests
Andarist Apr 19, 2023
97adac5
only use the aggregate inference when there are no other candidates
Andarist Apr 19, 2023
8ffcb94
do not collect index-based inferences from non-inferrable types
Andarist Apr 20, 2023
192d8b7
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist May 22, 2023
5fa585c
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Jun 13, 2023
375c127
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Aug 22, 2023
a62749c
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Sep 15, 2024
2f86371
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Sep 16, 2024
9825bcd
update baselines
Andarist Sep 16, 2024
46e280b
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Nov 28, 2025
c90fb20
instantiate aggregate inference
Andarist Nov 30, 2025
2b580c8
experiment with `eraseSelfMapper`
Andarist Dec 1, 2025
a390703
experiment further
Andarist Dec 1, 2025
15eda09
drop unused code
Andarist Dec 1, 2025
e3f6b43
discard never aggregate inferences
Andarist Dec 2, 2025
1911406
prefer default
Andarist Dec 2, 2025
20d6feb
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Dec 2, 2025
a554bbf
change condition for indexes gathering
Andarist Dec 2, 2025
22ddecc
simplify test
Andarist Dec 2, 2025
ced3cc1
refactor
Andarist Dec 2, 2025
a09f410
remove `PartialInference`
Andarist Dec 3, 2025
7bc77f1
add tests
Andarist Dec 3, 2025
097b8e6
Merge remote-tracking branch 'origin/main' into infer-concrete-proper…
Andarist Dec 5, 2025
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
109 changes: 86 additions & 23 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14665,23 +14665,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
inferredProp.declarations = prop.declarations;
inferredProp.links.nameType = getSymbolLinks(prop).nameType;
inferredProp.links.propertyType = getTypeOfSymbol(prop);
if (
type.constraintType.type.flags & TypeFlags.IndexedAccess
&& (type.constraintType.type as IndexedAccessType).objectType.flags & TypeFlags.TypeParameter
&& (type.constraintType.type as IndexedAccessType).indexType.flags & TypeFlags.TypeParameter
) {
// A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is
// inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of
// type identities produced, we simplify such indexed access occurences
const newTypeParam = (type.constraintType.type as IndexedAccessType).objectType;
const newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type as ReplaceableIndexedAccessType, newTypeParam);
inferredProp.links.mappedType = newMappedType as MappedType;
inferredProp.links.constraintType = getIndexType(newTypeParam) as IndexType;
}
else {
inferredProp.links.mappedType = type.mappedType;
inferredProp.links.constraintType = type.constraintType;
}
inferredProp.links.mappedType = type.mappedType;
inferredProp.links.constraintType = type.constraintType;
members.set(prop.escapedName, inferredProp);
}
setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos);
Expand Down Expand Up @@ -20569,7 +20554,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

/**
* Maps forward-references to later types parameters to the empty object type.
* Maps forward-references to later types parameters to the unknown type.
* This is used during inference when instantiating type parameter defaults.
*/
function createBackreferenceMapper(context: InferenceContext, index: number): TypeMapper {
Expand Down Expand Up @@ -26274,6 +26259,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
topLevel: true,
isFixed: false,
impliedArity: undefined,
indexes: undefined,
};
}

Expand All @@ -26287,6 +26273,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
topLevel: inference.topLevel,
isFixed: inference.isFixed,
impliedArity: inference.impliedArity,
indexes: inference.indexes && inference.indexes.slice(),
};
}

Expand Down Expand Up @@ -26372,6 +26359,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
* variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
*/
function inferTypeForHomomorphicMappedType(source: Type, target: MappedType, constraint: IndexType): Type | undefined {
// A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is
// inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of
// type identities produced, we simplify such indexed access occurences
if (constraint.type.flags & TypeFlags.IndexedAccess) {
const newTypeParam = (constraint.type as IndexedAccessType).objectType;
target = replaceIndexedAccess(target, constraint.type as ReplaceableIndexedAccessType, newTypeParam) as MappedType;
constraint = getIndexType(newTypeParam) as IndexType;
}
const cacheKey = source.id + "," + target.id + "," + constraint.id;
if (reverseHomomorphicMappedCache.has(cacheKey)) {
return reverseHomomorphicMappedCache.get(cacheKey);
Expand Down Expand Up @@ -26434,9 +26429,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function inferReverseMappedTypeWorker(sourceType: Type, target: MappedType, constraint: IndexType): Type {
const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)) as TypeParameter;
const typeParameter = getTypeParameterFromMappedType(target);
const inferenceTarget = getIndexedAccessType(constraint.type, typeParameter);
const templateType = getTemplateTypeFromMappedType(target);
const inference = createInferenceInfo(typeParameter);
const inference = createInferenceInfo(inferenceTarget);
inferTypes([inference], sourceType, templateType);
return getTypeFromInference(inference) || unknownType;
}
Expand Down Expand Up @@ -26507,7 +26503,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function getTypeFromInference(inference: InferenceInfo) {
return inference.candidates ? getUnionType(inference.candidates, UnionReduction.Subtype) :
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
undefined;
getAggregateInference(inference);
}

function hasSkipDirectInferenceFlag(node: Node) {
Expand Down Expand Up @@ -26879,6 +26875,23 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
inferFromTypes((source as IndexedAccessType).objectType, (target as IndexedAccessType).objectType);
inferFromTypes((source as IndexedAccessType).indexType, (target as IndexedAccessType).indexType);
}
else if (!(priority & InferencePriority.NakedTypeVariable) && target.flags & TypeFlags.IndexedAccess) {
if (isFromInferenceBlockedSource(source)) {
return;
}
const inference = getInferenceInfoForType(getActualTypeVariable((target as IndexedAccessType).objectType));
if (inference) {
if (getObjectFlags(source) & ObjectFlags.NonInferrableType || source === nonInferrableAnyType) {
return;
}
if (!hasInferenceCandidates(inference)) {
const recordSymbol = getGlobalRecordSymbol();
if (recordSymbol) {
inference.indexes = append(inference.indexes, getTypeAliasInstantiation(recordSymbol, [(target as IndexedAccessType).indexType, source]));
}
}
}
}
else if (source.flags & TypeFlags.StringMapping && target.flags & TypeFlags.StringMapping) {
if ((source as StringMappingType).symbol === (target as StringMappingType).symbol) {
inferFromTypes((source as StringMappingType).type, (target as StringMappingType).type);
Expand Down Expand Up @@ -27527,6 +27540,52 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return getWidenedType(unwidenedType);
}

function getAggregateInference(inference: InferenceInfo, constraintType?: Type, compareTypes?: TypeComparer, mapper?: TypeMapper | undefined): Type | undefined {
if (!inference.indexes) {
return undefined;
}
const typeEraser = createTypeEraser([inference.typeParameter.flags & TypeFlags.IndexedAccess ? (inference.typeParameter as IndexedAccessType).objectType : inference.typeParameter]);
const aggregateInference = instantiateType(getIntersectionType(inference.indexes), mapper ? mergeTypeMappers(typeEraser, mapper) : typeEraser);
if (getReducedType(aggregateInference).flags & TypeFlags.Never) {
// `never` inference isn't that useful of an inference given its assignable to every other type
return undefined;
}
if (!constraintType || (compareTypes ??= compareTypesAssignable)(aggregateInference, getTypeWithThisArgument(constraintType, aggregateInference))) {
return aggregateInference;
}
if (constraintType.flags & TypeFlags.Union) {
const discriminantProps = findDiscriminantProperties(getPropertiesOfType(aggregateInference), constraintType);
if (discriminantProps) {
let match: Type | undefined;
findDiscriminant:
for (const p of discriminantProps) {
const candidatePropType = getTypeOfPropertyOfType(aggregateInference, p.escapedName);
for (const type of (constraintType as UnionType).types) {
const propType = getTypeOfPropertyOfType(type, p.escapedName);
if (propType && candidatePropType && isTypeAssignableTo(candidatePropType, propType)) {
if (match && match !== type) {
match = undefined;
break findDiscriminant;
}
else {
match = type;
}
}
}
}
if (match) {
const combinedType = getSpreadType(match, aggregateInference, /*symbol*/ undefined, /*propegatedFlags*/ 0, /*readonly*/ false);
if (compareTypes(combinedType, getTypeWithThisArgument(constraintType, combinedType))) {
return combinedType;
}
}
}
}
// if the aggregate inference isn't assignable to the constraint return undefined
// this way the compiler keeps preferring the default type
return undefined;
}

function getInferredType(context: InferenceContext, index: number): Type {
const inference = context.inferences[index];
if (!inference.inferredType) {
Expand All @@ -27551,11 +27610,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType;
fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType;
}
else if (inference.indexes) {
const instantiatedConstraint = instantiateType(getConstraintOfTypeParameter(inference.typeParameter), context.nonFixingMapper);
inferredType = getAggregateInference(inference, instantiatedConstraint, context.compareTypes, context.nonFixingMapper);
}
else if (context.flags & InferenceFlags.NoDefault) {
// We use silentNeverType as the wildcard that signals no inferences.
inferredType = silentNeverType;
}
else {
if (!inferredType) {
// Infer either the default or the empty object type when no inferences were
// made. It is important to remember that in this case, inference still
// succeeds, meaning there is no error for not having inference candidates. An
Expand All @@ -27564,7 +27627,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const defaultType = getDefaultFromTypeParameter(inference.typeParameter);
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
// parameter should be instantiated to the unknown type.
inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
}
Expand Down
1 change: 1 addition & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7107,6 +7107,7 @@ export interface InferenceInfo {
typeParameter: TypeParameter; // Type parameter for which inferences are being made
candidates: Type[] | undefined; // Candidates in covariant positions (or undefined)
contraCandidates: Type[] | undefined; // Candidates in contravariant positions (or undefined)
indexes: Type[] | undefined; // Partial candidates created by indexed accesses
inferredType?: Type; // Cache for resolved inferred type
priority?: InferencePriority; // Priority of current inference set
topLevel: boolean; // True if all inferences are to top level occurrences
Expand Down
23 changes: 10 additions & 13 deletions tests/baselines/reference/correlatedUnions.types
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
//// [tests/cases/compiler/correlatedUnions.ts] ////

=== Performance Stats ===
Type Count: 1,000

=== correlatedUnions.ts ===
// Various repros from #30581

Expand Down Expand Up @@ -775,8 +772,8 @@ function ff1() {
> : ^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^

const funs: { [P in Keys]: (...args: ArgMap[P]) => void } = {
>funs : { concat: (a: string, b: string, c: string) => void; sum: (a: number, b: number) => void; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
>funs : { sum: (a: number, b: number) => void; concat: (a: string, b: string, c: string) => void; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
>args : { sum: [a: number, b: number]; concat: [a: string, b: string, c: string]; }[P]
> : ^^^^^^^ ^^^^^^^^^^ ^^^^^^
>{ sum: (a, b) => a + b, concat: (a, b, c) => a + b + c } : { sum: (a: number, b: number) => number; concat: (a: string, b: string, c: string) => string; }
Expand Down Expand Up @@ -829,20 +826,20 @@ function ff1() {
> : ^^^^^^^ ^^^^^^^^^^ ^^^^^^

const fn = funs[funKey];
>fn : { concat: (a: string, b: string, c: string) => void; sum: (a: number, b: number) => void; }[K]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
>funs[funKey] : { concat: (a: string, b: string, c: string) => void; sum: (a: number, b: number) => void; }[K]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
>funs : { concat: (a: string, b: string, c: string) => void; sum: (a: number, b: number) => void; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
>fn : { sum: (a: number, b: number) => void; concat: (a: string, b: string, c: string) => void; }[K]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
>funs[funKey] : { sum: (a: number, b: number) => void; concat: (a: string, b: string, c: string) => void; }[K]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
>funs : { sum: (a: number, b: number) => void; concat: (a: string, b: string, c: string) => void; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
>funKey : K
> : ^

fn(...args);
>fn(...args) : void
> : ^^^^
>fn : { concat: (a: string, b: string, c: string) => void; sum: (a: number, b: number) => void; }[K]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
>fn : { sum: (a: number, b: number) => void; concat: (a: string, b: string, c: string) => void; }[K]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
>...args : string | number
> : ^^^^^^^^^^^^^^^
>args : { sum: [a: number, b: number]; concat: [a: string, b: string, c: string]; }[K]
Expand Down
Loading