π Search Terms
"cannot be used to index type"
π Version & Regression Information
- This is the behavior in every version since 4.3. Before 4.3, CFA doesn't work.
β― Playground Link
https://www.typescriptlang.org/play?ts=5.3.0-dev.20230929#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXywGcAlEAcwFEAPABwAoqAueKVATwEpmqDD5TKtANwAoUJFgIweQhniEcAWxAB5AEYArZgG94AbULNZMLKjIBdZmpw4IIVvAC+okSnTY8SGwB4AkvBAqDBBUYD5jUzJ4AB9+cmoaAD4GZl8OeG0ReAJEeDoiAQSGDnTM7OyMKABrEBJ42mLRcvg4DGQYVCanLPhKmsIAZQwTM0b4AHpx+AB1BCrUHAB3eCZ5Ycj4AAsQOB6FZXUNPSpzIQmpgCFkOVksCAh4RYRgPAByOSh7pfg2HGRenDwZCEBA8RA4GAEUKBSIiRwiMTgaBwJBoTC4fBEIYjMgpFjsLgrXhrHEuNzozzgnAAJj8ASCITCJI2sUKtGSqzSGR6WFy+UG61GVBK3OafVq2MijR62X2qk0x1O53gABVNkRHhCqoQZS0QG0Ol14RVqrU2fRhaJ4YiJCjyR58OKBTi6IZmWZCQA3HBYYCicTIhD2jG9U11QT0N3mr0+v1AA
π» Code
declare function takesString(s: string): void;
declare function takesRegExp(s: RegExp): void;
declare function isRegExp(x: any): x is RegExp;
declare const someObj: { [s: string]: boolean };
function foo<I extends string | RegExp>(x: I) {
if (isRegExp(x)) {
takesRegExp(x);
return;
}
takesString(x); // We know x: string here
someObj[x]; // But still we don't allow you to use x for indexing
}
π Actual behavior
Error on someObj[x]: "Type 'I' cannot be used to index type '{ [s: string]: boolean; }'."
π Expected behavior
No error: from CFA we know the type of x is actually constrained to string.
Additional information about the issue
If we reverse the order of the checks, i.e. check if the type of x is string in the if, the indexing works:
function foo2<I extends string | RegExp>(x: I) {
if (isString(x)) {
takesString(x);
someObj[x]; // This works
return;
}
takesRegExp(x);
}
π Search Terms
"cannot be used to index type"
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?ts=5.3.0-dev.20230929#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXywGcAlEAcwFEAPABwAoqAueKVATwEpmqDD5TKtANwAoUJFgIweQhniEcAWxAB5AEYArZgG94AbULNZMLKjIBdZmpw4IIVvAC+okSnTY8SGwB4AkvBAqDBBUYD5jUzJ4AB9+cmoaAD4GZl8OeG0ReAJEeDoiAQSGDnTM7OyMKABrEBJ42mLRcvg4DGQYVCanLPhKmsIAZQwTM0b4AHpx+AB1BCrUHAB3eCZ5Ycj4AAsQOB6FZXUNPSpzIQmpgCFkOVksCAh4RYRgPAByOSh7pfg2HGRenDwZCEBA8RA4GAEUKBSIiRwiMTgaBwJBoTC4fBEIYjMgpFjsLgrXhrHEuNzozzgnAAJj8ASCITCJI2sUKtGSqzSGR6WFy+UG61GVBK3OafVq2MijR62X2qk0x1O53gABVNkRHhCqoQZS0QG0Ol14RVqrU2fRhaJ4YiJCjyR58OKBTi6IZmWZCQA3HBYYCicTIhD2jG9U11QT0N3mr0+v1AA
π» Code
π Actual behavior
Error on
someObj[x]: "Type 'I' cannot be used to index type '{ [s: string]: boolean; }'."π Expected behavior
No error: from CFA we know the type of
xis actually constrained tostring.Additional information about the issue
If we reverse the order of the checks, i.e. check if the type of
xisstringin theif, the indexing works: