loosen number index check, fixes #15768

This commit is contained in:
Tycho Grouwstra 2017-08-13 14:57:23 +08:00
parent d03d1074ee
commit 1d6863ab0b
5 changed files with 24 additions and 7 deletions

View file

@ -18758,13 +18758,12 @@ namespace ts {
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) && isTypeAssignableToKind(indexType, TypeFlags.NumberLike)) {
const constraint = getBaseConstraintOfType(objectType);
if (constraint && getIndexInfoOfType(constraint, IndexKind.Number)) {
return type;
}
// Check if we're indexing with a numeric type and if either object or index types
// is a generic type with a constraint that has a numeric index signature.
const typeOrConstraint = (tp: Type) => maybeTypeOfKind(tp, TypeFlags.TypeVariable) ? getBaseConstraintOfType(tp) || tp : tp;
if (isTypeAssignableToKind(typeOrConstraint(indexType), TypeFlags.NumberLike) &&
getIndexInfoOfType(typeOrConstraint(objectType), IndexKind.Number)) {
return type;
}
error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
return type;

View file

@ -0,0 +1,5 @@
//// [genericNumberIndex.ts]
type X<I extends number> = ['a'][I];
//// [genericNumberIndex.js]

View file

@ -0,0 +1,6 @@
=== tests/cases/compiler/genericNumberIndex.ts ===
type X<I extends number> = ['a'][I];
>X : Symbol(X, Decl(genericNumberIndex.ts, 0, 0))
>I : Symbol(I, Decl(genericNumberIndex.ts, 0, 7))
>I : Symbol(I, Decl(genericNumberIndex.ts, 0, 7))

View file

@ -0,0 +1,6 @@
=== tests/cases/compiler/genericNumberIndex.ts ===
type X<I extends number> = ['a'][I];
>X : ["a"][I]
>I : I
>I : I

View file

@ -0,0 +1 @@
type X<I extends number> = ['a'][I];