Why is the infer keyword needed in Typescript?

CodyBugstein picture CodyBugstein · Feb 5, 2020 · Viewed 8.5k times · Source

Why did the Typescript folks create the infer keyword? According to the documents, this is an example of how you would use it:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

I don't understand why this is needed. Why can't it just be:

type ReturnType<T> = T extends (...args: any[]) => R ? R : any;

Why doesn't this work? Why is the infer keyword necessary ?

Answer

kaya3 picture kaya3 · Feb 5, 2020

Consider the following code:

interface Example {
    foo: string
}

type GenericExample<T> = T extends Examlep ? 'foo' : 'bar';

This code should result in a compilation error, because Examlep is spelled incorrectly; there is no type named Examlep, and obviously the programmer meant to write Example here.

Now imagine the infer keyword is not needed in an extends clause of a conditional type. Then the above code would not give a compilation error; it would see that there is no type named Examlep, infer what type it is, and then (since Examlep has no constraints) observe that T does indeed extend Examlep for the inferred type.

In that case, GenericExample<T> would always be 'foo' regardless of what T is, and there would be no compilation error to inform the programmer about the mistake. This would be the wrong thing for the compiler to do, almost all of the time.