- Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixedConstraints of the existing architecture prevent this from being fixed
Milestone
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
declarefunctiontakesString(s: string): void;declarefunctiontakesRegExp(s: RegExp): void;declarefunctionisRegExp(x: any): x is RegExp;declareconstsomeObj: {[s: string]: boolean};functionfoo<Iextendsstring|RegExp>(x: I){if(isRegExp(x)){takesRegExp(x);return;}takesString(x);// We know x: string heresomeObj[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:
functionfoo2<Iextendsstring|RegExp>(x: I){if(isString(x)){takesString(x);someObj[x];// This worksreturn;}takesRegExp(x);}so1ve
Metadata
Metadata
Assignees
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixedConstraints of the existing architecture prevent this from being fixed