Skip to content

T[keyof T] should be never for T={} #22042

Closed
@yortus

Description

@yortus

TypeScript Version: 2.8.0-dev.20180216

Search Terms:

  • indexed access type
  • keyof
  • never

Code

type A = {};
type B = A[keyof A];    // B = any
        // ^^^^^^^      // ERROR: 'never' cannot be used as an index type

Expected behavior:
A[keyof A] is a valid indexed access type that evaluated to never.

Actual behavior:
A[keyof A] is treated as an error, and evaluates to any (presumably due to compiler bailout).

Related Issues:

#11929 describes indexed access types as follows:

An indexed access type T[K] requires K to be a type that is assignable to keyof T [...] and yields the type of the property or properties in T selected by K.

In this case K=never and T={}, so K is assignable to keyof T, so T[K] appears to be a valid type.

The union of zero property keys is never, as tsc shows with keyof {} = never.

So the result should be the union of zero property types, i.e. also never.

Consequences:

In more complex generics this leads to meaningful problems, e.g. in #21988 where RequiredProps<{}> evalutes to {[x: string]: any} when it should be {}.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions