Simplify indexed accesses on mapped types with no depth limit

This commit is contained in:
Anders Hejlsberg 2018-12-11 15:11:57 -08:00
parent 02b13a916a
commit 0dcaaa5c50

View File

@ -67,7 +67,6 @@ namespace ts {
let enumCount = 0;
let instantiationDepth = 0;
let constraintDepth = 0;
let simplificationDepth = 0;
const emptySymbols = createSymbolTable();
const identityMapper: (type: Type) => Type = identity;
@ -9687,31 +9686,15 @@ namespace ts {
// If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>. Mapped types can be recursive so to guard against infinite recursion we
// only perform this simplification up to five levels deep.
if (simplificationDepth < 5) {
if (isGenericMappedType(objectType)) {
return type.simplified = substituteIndexedMappedType(objectType, type);
}
if (objectType.flags & TypeFlags.TypeParameter) {
const constraint = getConstraintOfTypeParameter(objectType as TypeParameter);
if (constraint && isGenericMappedType(constraint)) {
return type.simplified = substituteIndexedMappedType(constraint, type);
}
}
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
const templateMapper = combineTypeMappers(objectType.mapper, mapper);
return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
}
return type.simplified = type;
}
function substituteIndexedMappedType(objectType: MappedType, type: IndexedAccessType) {
simplificationDepth++;
const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
const templateMapper = combineTypeMappers(objectType.mapper, mapper);
const result = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
simplificationDepth--;
return result;
}
function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName, missingType = accessNode ? errorType : unknownType): Type {
if (objectType === wildcardType || indexType === wildcardType) {
return wildcardType;