What does never do in Array<string>[never]?

For example,

type A = Array<string>[never]; // A is string

How to understand never here? For example, can we use any here? and what is the difference if any?


Generally T[K] is a indexed type access. Where K needs to be a possible key of T. So Array<string>[never] is an indexed type access where T is Array<string> and K is never.

To understand why Array<string>[never] works, let's first see what you could and couldn't index Array<string> with:

  1. You can't index with string ( Array<string>[string] is an error) This is because Array does not have a index signature, so indexing with a random string is not allowed.
  2. You could index with a specific string literal type representing a member of Array (ex Array<string>['map'] works)
  3. You can index with number, as Array has an index signature with for number (ex: Array<string>[number] is string)
  4. You can index with a subtype of number. For example you can index with the number literal type 0. Here TS will look for an index signature that can be matched to the number literal type and it will find the number index signature. It will match this index signature because 0 is assignable to number. So Array<string>[0] will be string

So why can we index with never? Well never is by definition the subtype of any other type (ie, it is assignable to any other type). This means never is also a subtype of, and assignable to number (ex). Since never is a subtype of number, the number signature can be used to index with never, just as it can be used for 0. This is why Array<string>[never] resolves to string