DEV Community

Acid Coder
Acid Coder

Posted on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay