DEV Community

Acid Coder
Acid Coder

Posted on

Typescript WTF Moments 10: The Special Case: T[] extends B[]

observe the below example:

type A = boolean;
type B = string; 
type C<T extends B> = {

}
type D<T extends B|A> = T extends B ? C<T> : never
type E<T extends B|A> = [T] extends [B] ? C<T> : never
type F<T extends B|A> = T[] extends B[] ? C<T> : never // ERROR !!!!
Enter fullscreen mode Exit fullscreen mode

Image description

playground

It errors, and errors in a place that you don't expect

the error message:

Image description

Now normally when we extends something don't expect, it will narrow down the type, eg:

type A<T extends string, number> = T extends string ? T : never
Enter fullscreen mode Exit fullscreen mode

Image description

in the above code, the highlighted T is narrowed down to string

And as you can see, this is not the case with T[] extends B[]

Now what if I tell you I lied? The error of T[] extends B[] is work as expected, what is not expected is [T] extends [B]

with T[] extends B[] the compiler will not narrow the type like how it narrow down T extends B

But [T] extends [B] is a special case in the compiler, compiler will narrow down [T] extends [B] like T extends B, which is why [T] extends [B] does not error

The error of T[] extends B[] is expected because T[] extends B[] suppose to narrow down T[] not T.

tips: another thing is both T[] extends B[] and [T] extends [B] both do not distribute

Top comments (0)