Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

typescript - Why this CustomExtract returns an different result from default Extract?

The code explains my question:

type A = {
  a: number,
} | null

// Extract as defined in lib.es5.d.ts
type Extract<T, U> = T extends U ? T : never;

type CustomExtract = A extends null ? A : never;

type Result1 = Extract<A, null> // null
type Result2 = CustomExtract;   // never

Extract and CustomExtract are the same code, with the difference that Extract is a generic type.

Also, as related example, string | null does not extends null.

So, how types really works under the hoods at this topic? I can imagine it maybe runs the generic type for each type of the union and then unionize all the results, but I want the real technical definition and working of it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...