Skip to content

Narrowed type not used when indexing#55922

@gabritto

Description

@gabritto

🔎 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

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);}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions