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:
- You can't index with
string
(Array<string>[string]
is an error) This is becauseArray
does not have a index signature, so indexing with a random string is not allowed. - You could index with a specific
string
literal type representing a member ofArray
(exArray<string>['map']
works) - You can index with
number
, asArray
has an index signature with fornumber
(ex:Array<string>[number]
isstring
) - 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 because0
is assignable tonumber
. SoArray<string>[0]
will bestring
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