From 919e682e3f53ee8dbc914c27d04763406e29becb Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 16 Jan 2017 12:18:01 -0800 Subject: [PATCH] Allow T[N] where N is numeric and T has apparent numeric index signature --- src/compiler/checker.ts | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 80516ef9319..9ea61bc2655 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16032,14 +16032,24 @@ namespace ts { } function checkIndexedAccessIndexType(type: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode) { - if (type.flags & TypeFlags.IndexedAccess) { - // Check that the index type is assignable to 'keyof T' for the object type. - const objectType = (type).objectType; - const indexType = (type).indexType; - if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { - error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + if (!(type.flags & TypeFlags.IndexedAccess)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + const objectType = (type).objectType; + const indexType = (type).indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + return type; + } + // Check if we're indexing with a numeric type and the object type is a generic + // type with a constraint that has a numeric index signature. + if (maybeTypeOfKind(objectType, TypeFlags.TypeVariable) && isTypeOfKind(indexType, TypeFlags.NumberLike)) { + const constraint = getBaseConstraintOfType(objectType); + if (constraint && getIndexInfoOfType(constraint, IndexKind.Number)) { + return type; } } + error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); return type; }