Function and Inference Return Types
In this lesson, we will cover functions inference with many types along with the evolution of returns.
We'll cover the following
Inference with many types
Functions can return an implicit or explicit type. By default, TypeScript returns a void type. However, if not specified and the code returns a number, the return type would implicitly be a number. If later the function returns a string, what is the expected return value? This lack of clarity can lead to confusion while having the flexibility of returning an array of potential types.
It is possible to return more than a single type by using a union and still restrict potential return type. The unpredictability of the return type is the reason why having an explicit return type is always a better practice than relying on inference. Explicitly mentioning the type defines a clear contract that cannot change without manually altering the return type.
Get hands-on with 1200+ tech skills courses.