Closed
Description
π 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
π» 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);
}