Skip to content
Open
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
85 changes: 67 additions & 18 deletions tsc/internal/checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ const (
CachedTypeKindDecoratorContextStatic
CachedTypeKindDecoratorContextPrivate
CachedTypeKindDecoratorContextPrivateStatic
CachedTypeKindNonDistributedConditionalType
CachedTypeKindNonDistributedType
CachedTypeKindSimplifiedConditionalTypeForReading
CachedTypeKindSimplifiedConditionalTypeForWriting
)
Expand Down Expand Up @@ -23898,26 +23898,44 @@ func (c *Checker) getTypeFromTypeReference(node *ast.Node) *Type {

func (c *Checker) getDistributedTypeParameter(node *ast.Node, t *Type) *Type {
if t.flags&TypeFlagsTypeParameter != 0 && !t.AsTypeParameter().isDistributed && c.isInDistributiveContext(node, t.symbol) {
// If node is contained in a distributive conditional type for the given type parameter,
// If node is contained in a distributive context for the given type parameter,
// return the distributed form of the type parameter.
return c.getDistributedTypeFromTypeParameter(t)
}
return t
}

// Returns true if the node is, or is contained in, a distributive conditional type for the given type
// parameter symbol, or for any type parameter when symbol is nil. Types declared in such a context may
// reference distributed type parameters, so their identity instantiation isn't the declared type itself
// (instantiation maps distributed type parameters back to their non-distributed form).
// Returns true if the node is, or is contained in, a distributive context for the given type parameter
// symbol, or for any type parameter when symbol is nil. A distributive context is a distributive conditional
// type 'T extends U ? X : Y' or the template of a homomorphic mapped type '{ [K in keyof T]: X }', both of
// which distribute over union types for T. Types declared in such a context may reference distributed type
// parameters, so their identity instantiation isn't the declared type itself (instantiation maps distributed
// type parameters back to their non-distributed form).
func (c *Checker) isInDistributiveContext(node *ast.Node, symbol *ast.Symbol) bool {
for n := node; n != nil && !ast.IsStatement(n); n = n.Parent {
if ast.IsConditionalTypeNode(n) {
if checkTypeNode := n.AsConditionalTypeNode().CheckType; isSimpleIdentifierTypeReference(checkTypeNode) {
if s := c.getSymbolFromTypeReference(checkTypeNode); s != nil && s.Flags()&ast.SymbolFlagsTypeParameter != 0 && (symbol == nil || s == symbol) {
return true
var child *ast.Node
for n := node; n != nil && !ast.IsStatement(n); child, n = n, n.Parent {
var typeParameterNode *ast.Node
switch {
case ast.IsConditionalTypeNode(n):
typeParameterNode = ast.SkipTypeParentheses(n.AsConditionalTypeNode().CheckType)
case ast.IsMappedTypeNode(n):
// The template and name type of a homomorphic mapped type are distributive contexts, but its
// 'keyof T' constraint is not: the constraint of the mapped type's type parameter is shared by
// all instantiations of the mapped type and must stay in terms of the non-distributed form.
m := n.AsMappedTypeNode()
if child == nil || child == m.Type || child == m.NameType {
if constraint := m.TypeParameter.AsTypeParameterDeclaration().Constraint; constraint != nil {
if constraint := ast.SkipTypeParentheses(constraint); ast.IsTypeOperatorNode(constraint) && constraint.AsTypeOperatorNode().Operator == ast.KindKeyOfKeyword {
typeParameterNode = ast.SkipTypeParentheses(constraint.Type())
Comment on lines +23928 to +23929

@Andarist Mateusz Burzyński (Andarist) Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a gap in the original design of distributed type parameters, which only recognizes a type parameter referenced directly. Conditional types have it too: Alias<T> extends unknown ? Show<T, U> : never distributes over T but reports no error. Mapped types follow the same syntactic rule here, so I am leaving this out of this PR.

Proof:

type Show<A, B extends A> = [A, B] & {};

type Working<A, B extends A> = A extends unknown
  ? B extends unknown
    ? Show<A, B> // Error!
    : never
  : never;

type Alias<P> = P

type Issue<A, B extends A> = Alias<A> extends unknown
  ? B extends unknown
    ? Show<A, B> // No error :(
    : never
  : never;

type X = Issue<0 | 1, 0 | 1>;
// type X = [0, 0] | [0, 1] | [1, 0] | [1, 1] // so this *does* distribute despite the alias

}
}
}
}
if typeParameterNode != nil && isSimpleIdentifierTypeReference(typeParameterNode) {
if s := c.getSymbolFromTypeReference(typeParameterNode); s != nil && s.Flags()&ast.SymbolFlagsTypeParameter != 0 && (symbol == nil || s == symbol) {
return true
}
}
}
return false
}
Expand All @@ -23933,20 +23951,51 @@ func (c *Checker) getDistributedTypeFromTypeParameter(t *Type) *Type {
}

// Returns the given conditional type with references to the distributed form of its check type parameter
// mapped back to the non-distributed form. This is the identity instantiation of the conditional type,
// which is cached in the instantiation map of the conditional type's root.
// mapped back to the non-distributed form.
func (c *Checker) getNonDistributedConditionalType(t *Type) *Type {
checkType := t.AsConditionalType().checkType
typeParameter := getNonDistributedTypeParameter(checkType)
if typeParameter == checkType {
result := c.getNonDistributedType(t, t.AsConditionalType().checkType)
debug.Assert(result.flags&TypeFlagsConditional != 0, "Identity instantiation of a conditional type should remain deferred")
return result
}

// Returns the given generic mapped type with references to the distributed form of its homomorphic type
// variable mapped back to the non-distributed form. Only declared mapped types need this, as instantiation
// already maps distributed type parameters back to their non-distributed form. A type variable that is itself
// distributed comes from an enclosing distributive context and must keep its distributed form.
func (c *Checker) getNonDistributedMappedType(t *Type) *Type {
if t.AsMappedType().target != nil {
return t
}
key := CachedTypeKey{kind: CachedTypeKindNonDistributedConditionalType, typeId: t.id}
constraintType := c.getConstraintTypeFromMappedType(t)
if constraintType.flags&TypeFlagsIndex == 0 {
return t
}
typeVariable := constraintType.AsIndexType().target
if typeVariable.flags&TypeFlagsSubstitution != 0 {
typeVariable = typeVariable.AsSubstitutionType().baseType
}
if typeVariable.flags&TypeFlagsTypeParameter == 0 || typeVariable.AsTypeParameter().isDistributed {
return t
Comment on lines +23977 to +23978
}
result := c.getNonDistributedType(t, c.getDistributedTypeFromTypeParameter(typeVariable))
debug.Assert(result.objectFlags&ObjectFlagsMapped != 0, "Identity instantiation of a generic mapped type should remain a mapped type")
return result
}

// Returns the identity instantiation of the given type for the non-distributed form of the given type
// variable if it is a distributed type parameter, and otherwise the type itself. Instantiation maps all
// occurrences of distributed type parameters back to their non-distributed form, so the result is the
// given type with distributed type parameters replaced by their non-distributed form.
func (c *Checker) getNonDistributedType(t *Type, typeVariable *Type) *Type {
typeParameter := getNonDistributedTypeParameter(typeVariable)
if typeParameter == typeVariable {
return t
}
key := CachedTypeKey{kind: CachedTypeKindNonDistributedType, typeId: t.id}
if cached := c.cachedTypes[key]; cached != nil {
return cached
}
result := c.instantiateType(t, newSimpleTypeMapper(typeParameter, typeParameter))
debug.Assert(result.flags&TypeFlagsConditional != 0, "Identity instantiation of a conditional type should remain deferred")
c.cachedTypes[key] = result
return result
}
Expand Down
10 changes: 7 additions & 3 deletions tsc/internal/checker/inference.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,7 @@ func (c *Checker) inferToTemplateLiteralType(n *InferenceState, source *Type, ta
func (c *Checker) inferFromGenericMappedTypes(n *InferenceState, source *Type, target *Type) {
// The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
// from S to T and from X to Y.
source = c.getNonDistributedMappedType(source)
c.inferFromTypes(n, c.getConstraintTypeFromMappedType(source), c.getConstraintTypeFromMappedType(target))
c.inferFromTypes(n, c.getTemplateTypeFromMappedType(source), c.getTemplateTypeFromMappedType(target))
sourceNameType := c.getNameTypeFromMappedType(source)
Expand Down Expand Up @@ -970,7 +971,7 @@ func (c *Checker) inferToMappedType(n *InferenceState, source *Type, target *Typ
// where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
// type and then make a secondary inference from that type to T. We make a secondary inference
// such that direct inferences to T get priority over inferences to Partial<T>, for example.
inference := getInferenceInfoForType(n, constraintType.AsIndexType().target)
inference := getInferenceInfoForType(n, c.getActualTypeVariable(constraintType.AsIndexType().target))
if inference != nil && !inference.isFixed && !c.isFromInferenceBlockedSource(source) {
inferredType := c.inferTypeForHomomorphicMappedType(source, target, constraintType)
if inferredType != nil {
Expand Down Expand Up @@ -1101,7 +1102,7 @@ func (c *Checker) inferReverseMappedType(source *Type, target *Type, constraint
}

func (c *Checker) inferReverseMappedTypeWorker(source *Type, target *Type, constraint *Type) *Type {
typeParameter := c.getIndexedAccessType(constraint.AsIndexType().target, c.getTypeParameterFromMappedType(target))
typeParameter := c.getIndexedAccessType(c.getActualTypeVariable(constraint.AsIndexType().target), c.getTypeParameterFromMappedType(target))
templateType := c.getTemplateTypeFromMappedType(target)
inference := newInferenceInfo(typeParameter)
c.inferTypes([]*InferenceInfo{inference}, source, templateType, InferencePriorityNone, false)
Expand Down Expand Up @@ -1196,7 +1197,10 @@ func (c *Checker) replaceIndexedAccess(instantiable *Type, t *Type, replacement
// map type.indexType to 0
// map type.objectType to `[TReplacement]`
// thus making the indexed access `[TReplacement][0]` or `TReplacement`
return c.instantiateType(instantiable, newTypeMapper([]*Type{t.AsIndexedAccessType().indexType, t.AsIndexedAccessType().objectType}, []*Type{c.getNumberLiteralType(0), c.createTupleType([]*Type{replacement})}))
// Mappers look up distributed type parameters by their non-distributed form, so the sources must use that form too.
indexType := getNonDistributedTypeParameter(t.AsIndexedAccessType().indexType)
objectType := getNonDistributedTypeParameter(t.AsIndexedAccessType().objectType)
return c.instantiateType(instantiable, newTypeMapper([]*Type{indexType, objectType}, []*Type{c.getNumberLiteralType(0), c.createTupleType([]*Type{replacement})}))
}

func (c *Checker) typesDefinitelyUnrelated(source *Type, target *Type) bool {
Expand Down
8 changes: 7 additions & 1 deletion tsc/internal/checker/relater.go
Original file line number Diff line number Diff line change
Expand Up @@ -3655,6 +3655,7 @@ func (r *Relater) structuredTypeRelatedToWorker(source *Type, target *Type, repo
}
case r.c.isGenericMappedType(target) && r.relation != r.c.identityRelation:
// Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`.
target := r.c.getNonDistributedMappedType(target)
keysRemapped := target.AsMappedType().declaration.NameType != nil
templateType := r.c.getTemplateTypeFromMappedType(target)
modifiers := getMappedTypeModifiers(target)
Expand Down Expand Up @@ -4042,6 +4043,11 @@ func (r *Relater) mappedTypeRelatedTo(source *Type, target *Type, reportErrors b
r.relation == r.c.identityRelation && getMappedTypeModifiers(source) == getMappedTypeModifiers(target) ||
r.relation != r.c.identityRelation && r.c.getCombinedMappedTypeOptionality(source) <= r.c.getCombinedMappedTypeOptionality(target)
if modifiersRelated {
// The constituent types of a homomorphic mapped type reference the distributed form of its type
// variable. The source constituents are instantiated below, which maps them back to the non-distributed
// form, but the target ones are related as is, so normalize the target to make the comparison not
// depend on whether it has been instantiated.
target := r.c.getNonDistributedMappedType(target)
targetConstraint := r.c.getConstraintTypeFromMappedType(target)
sourceConstraint := r.c.instantiateType(r.c.getConstraintTypeFromMappedType(source), core.IfElse(r.c.getCombinedMappedTypeOptionality(source) < 0, r.c.reportUnmeasurableMapper, r.c.reportUnreliableMapper))
if result := r.isRelatedTo(targetConstraint, sourceConstraint, RecursionFlagsBoth, reportErrors); result != TernaryFalse {
Expand Down Expand Up @@ -4656,7 +4662,7 @@ func (r *Relater) indexSignaturesRelatedTo(source *Type, target *Type, sourceIsP
case r.relation != r.c.strictSubtypeRelation && !sourceIsPrimitive && targetHasStringIndex && targetInfo.valueType.flags&TypeFlagsAny != 0:
related = TernaryTrue
case r.c.isGenericMappedType(source) && targetHasStringIndex:
related = r.isRelatedTo(r.c.getTemplateTypeFromMappedType(source), targetInfo.valueType, RecursionFlagsBoth, reportErrors)
related = r.isRelatedTo(r.c.getTemplateTypeFromMappedType(r.c.getNonDistributedMappedType(source)), targetInfo.valueType, RecursionFlagsBoth, reportErrors)
default:
related = r.typeRelatedToIndexInfo(source, targetInfo, reportErrors, intersectionState)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@ func TestQuickInfoDistributedTypeParameter(t *testing.T) {
? T/*trueType*/
: T/*falseType*/;

type Mapped<T> = { [P in keyof T/*mappedConstraint*/]: T/*mappedType*/ };

type MappedAs<T> = { [P in keyof T as T/*mappedNameType*/ extends unknown ? P : never]: T };

type NonDistributed<T> = [T/*nonDistributed*/] extends [unknown] ? T : never;`
f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
defer done()
f.VerifyQuickInfoAt(t, "check", "(type parameter) (distributed) T in type Conditional<T>", "")
f.VerifyQuickInfoAt(t, "extends", "(type parameter) (distributed) T in type Conditional<T>", "")
f.VerifyQuickInfoAt(t, "trueType", "(type parameter) (distributed) T in type Conditional<T>", "")
f.VerifyQuickInfoAt(t, "falseType", "(type parameter) (distributed) T in type Conditional<T>", "")
f.VerifyQuickInfoAt(t, "mappedConstraint", "(type parameter) T in type Mapped<T>", "")
f.VerifyQuickInfoAt(t, "mappedType", "(type parameter) (distributed) T in type Mapped<T>", "")
f.VerifyQuickInfoAt(t, "mappedNameType", "(type parameter) (distributed) T in type MappedAs<T>", "")
f.VerifyQuickInfoAt(t, "nonDistributed", "(type parameter) T in type NonDistributed<T>", "")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//// [tests/cases/compiler/distributedMappedTypeIndexSignature.ts] ////

=== distributedMappedTypeIndexSignature.ts ===
type Alias<T> = { [K in keyof T]: (state: T) => void };
>Alias : Symbol(Alias, Decl(distributedMappedTypeIndexSignature.ts, 0, 0))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 0, 11))
>K : Symbol(K, Decl(distributedMappedTypeIndexSignature.ts, 0, 19))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 0, 11))
>state : Symbol(state, Decl(distributedMappedTypeIndexSignature.ts, 0, 35))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 0, 11))

type Check<T, X extends { [x: string]: (state: T) => void }> = X;
>Check : Symbol(Check, Decl(distributedMappedTypeIndexSignature.ts, 0, 55))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 1, 11))
>X : Symbol(X, Decl(distributedMappedTypeIndexSignature.ts, 1, 13))
>x : Symbol(x, Decl(distributedMappedTypeIndexSignature.ts, 1, 27))
>state : Symbol(state, Decl(distributedMappedTypeIndexSignature.ts, 1, 40))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 1, 11))
>X : Symbol(X, Decl(distributedMappedTypeIndexSignature.ts, 1, 13))

type Use1<T> = Check<T, Alias<T>>;
>Use1 : Symbol(Use1, Decl(distributedMappedTypeIndexSignature.ts, 1, 65))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 2, 10))
>Check : Symbol(Check, Decl(distributedMappedTypeIndexSignature.ts, 0, 55))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 2, 10))
>Alias : Symbol(Alias, Decl(distributedMappedTypeIndexSignature.ts, 0, 0))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 2, 10))

type Use2<T> = Check<T, { [K in keyof T]: (state: T) => void }>;
>Use2 : Symbol(Use2, Decl(distributedMappedTypeIndexSignature.ts, 2, 34))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 3, 10))
>Check : Symbol(Check, Decl(distributedMappedTypeIndexSignature.ts, 0, 55))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 3, 10))
>K : Symbol(K, Decl(distributedMappedTypeIndexSignature.ts, 3, 27))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 3, 10))
>state : Symbol(state, Decl(distributedMappedTypeIndexSignature.ts, 3, 43))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 3, 10))

function f<T>(alias: Alias<T>, inline: { [K in keyof T]: (state: T) => T[K] }) {
>f : Symbol(f, Decl(distributedMappedTypeIndexSignature.ts, 3, 64))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>alias : Symbol(alias, Decl(distributedMappedTypeIndexSignature.ts, 5, 14))
>Alias : Symbol(Alias, Decl(distributedMappedTypeIndexSignature.ts, 0, 0))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>inline : Symbol(inline, Decl(distributedMappedTypeIndexSignature.ts, 5, 30))
>K : Symbol(K, Decl(distributedMappedTypeIndexSignature.ts, 5, 42))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>state : Symbol(state, Decl(distributedMappedTypeIndexSignature.ts, 5, 58))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>K : Symbol(K, Decl(distributedMappedTypeIndexSignature.ts, 5, 42))

const a: Record<string, (state: T) => unknown> = alias;
>a : Symbol(a, Decl(distributedMappedTypeIndexSignature.ts, 6, 9))
>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --))
>state : Symbol(state, Decl(distributedMappedTypeIndexSignature.ts, 6, 29))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>alias : Symbol(alias, Decl(distributedMappedTypeIndexSignature.ts, 5, 14))

const b: Record<string, (state: T) => unknown> = inline;
>b : Symbol(b, Decl(distributedMappedTypeIndexSignature.ts, 7, 9))
>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --))
>state : Symbol(state, Decl(distributedMappedTypeIndexSignature.ts, 7, 29))
>T : Symbol(T, Decl(distributedMappedTypeIndexSignature.ts, 5, 11))
>inline : Symbol(inline, Decl(distributedMappedTypeIndexSignature.ts, 5, 30))
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//// [tests/cases/compiler/distributedMappedTypeIndexSignature.ts] ////

=== distributedMappedTypeIndexSignature.ts ===
type Alias<T> = { [K in keyof T]: (state: T) => void };
>Alias : Alias<T>
>state : T

type Check<T, X extends { [x: string]: (state: T) => void }> = X;
>Check : X
>x : string
>state : T

type Use1<T> = Check<T, Alias<T>>;
>Use1 : Alias<T>

type Use2<T> = Check<T, { [K in keyof T]: (state: T) => void }>;
>Use2 : { [K in keyof T]: (state: T) => void; }
>state : T

function f<T>(alias: Alias<T>, inline: { [K in keyof T]: (state: T) => T[K] }) {
>f : <T>(alias: Alias<T>, inline: { [K in keyof T]: (state: T) => T[K]; }) => void
>alias : Alias<T>
>inline : { [K in keyof T]: (state: T) => T[K]; }
>state : T

const a: Record<string, (state: T) => unknown> = alias;
>a : Record<string, (state: T) => unknown>
>state : T
>alias : Alias<T>

const b: Record<string, (state: T) => unknown> = inline;
>b : Record<string, (state: T) => unknown>
>state : T
>inline : { [K in keyof T]: (state: T) => T[K]; }
}

Loading