Skip to content

Narrowed type not used when indexingΒ #55922

Closed
@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

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

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