Below is the implementation of Exclude
floating around on various blogs ( One Reference)
type Exclude<T, U> = T extends U ? never : T;
According to Typescript blog, it constructs a new type by excluding some properties from the union type. Perfect, I get it.
Let's detail this out.
If T
extends U
it returns never. Fair enough. Extends means that we are inheriting all properties. ( Reference - https://stackoverflow.com/a/38834997/1096194)
Confusion is that if ternary condition returns false, Shouldn't it return T - U
instead of T as we may want to return only T - U
properties in case T
is not an extension of U
.
Let's take an example #1
U = "name", T = "id" | "name";
If I understand correctly, T
extends U
is false in this case as T
did not inherit all properties from U
. So, we should return T-U
i.e. "id" which is the desired output of exclude operator.
Let's take another example #2
U = "name", T = "id" | "email"
In this case too, ternary fails as the T
does not extend or inherits anything from U
. So it should return T - U
i.e. id | email
happens to be equal to T
in this case.
So, what is the correct definition anyway i.e. T extends U? never: T
or T extends U? never: T - U
?