Why Not Use Return Type and What to Use Instead

June 17, 2023

In TypeScript, the return type of a function is a type of value that the function returns. Specifying the return type of a function is considered a good practice, as it helps to catch bugs early and make the code more readable. However, there are cases where it may not be necessary to specify the return type of a function. In this article, we will explore when to use return types and when to avoid them.

Let's consider the following example:

index.ts
1const foo = (): boolean => {
2 return true
3}
4
5const bar = (baz: boolean): boolean => {
6 return baz
7}
8
9bar(foo())

In this example, foo returns a boolean value, and bar takes a boolean argument and returns a boolean value. If we were to change the return type of foo to string, we would also need to change the return type of bar and the type of the baz argument to string.

index.ts
1const foo = (): string => {
2 return 'true'
3}
4
5const bar = (baz: string): string => {
6 return baz
7}
8
9bar(foo())

If the return type of foo and bar is not specified, TypeScript can infer it based on the value returned by the function. For example:

index.ts
1const foo = () => {
2 return 1
3}
4
5const bar = (baz: number) => {
6 return baz
7}
8
9bar(foo())

In this case, TypeScript infers that foo returns a number, and bar takes a number argument and returns a number value.

TypeScript provides a ReturnType utility type that can be used to infer the return type of a function. By using ReturnType, the return type of a function can be inferred, providing type inference and type safety. For example:

index.ts
1const foo = () => {
2 return 1
3}
4
5const bar = (baz: ReturnType<typeof foo>) => {
6 return baz
7}
8
9bar(foo())

In this example, TypeScript infers that foo returns a number, and bar takes an argument of the same type as the return type of foo.

Conclusion

In conclusion, specifying return types in TypeScript is a good practice to help catch bugs early and make code more readable. However, it is not always necessary to specify return types. TypeScript can infer them based on the value returned by the function. The ReturnType utility type can be used to infer the return type of a function, providing type inference and type safety. It is important to note that some special cases may require specifying the return type of a function, such as when using a third-party library without type definitions.

Share this post on Twitter