What @jcalz has said is all correct, but I'm going to try to put this is plain English.
What Extract<T, U>
does is return the subset of T
which is assignable to U
. If T
has some U
types and some other types, we get just the U
types. Why and how it does this, despite having a definition that looks the same as CustomExtract
, that is @jcalz's answer.
In your case, type A
is the union of {a: number}
and null
. {a: number}
is not assignable to null
, but null
is assignable to null
. So the subset which is assignable to null
is null
.
type CustomExtract = A extends null ? A : never;
will never return a subset. If the condition is met then it returns A
in its entirety and if the condition is not met then it returns never
.
In order for X extends Y
to be true, all values of X
must be assignable to Y
or in other words, X
must be equal to or narrower than Y
.
A extends null
is false because A
is broader than null
. On the other hand, null extends A
is true.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…