theProCoder
theProCoder

Reputation: 435

Confused about Typescript Function Return Types

I am a bit confused about the following typescript code:

function greet(name: string): string {
    return `Hello ${name}`;
}

function logGreeting(name: string): void {
    console.log(`Hello ${name}`);
}

function doSomething(name: string, callbackFn: (name: string) => void) {
    callbackFn(name);
}

doSomething('Zion', logGreeting);
doSomething('John', greet);

It is the last line of this code snippet that confuses me. In the doSomething function, I specify that callbackFn should take in name, which should be a string, and that it should return nothing (void).

But, in the doSomething('John', greet), greet doesn't return void, and yet Typescript doesn't throw an error. Why is this happening?

Thanks!

Upvotes: 2

Views: 2846

Answers (2)

Acuao
Acuao

Reputation: 691

Here's is my interpretation of this behavior :

You're telling Typescript that you want a function which doesn't return anything by specifying void but you already know that. So Typescript doesn't care about what is returned by your callback, because - in the end - it won't allow you to use it.

If you change your expected return type to string, then you will get an error if your callback function doesn't return a string.

I wasn't aware of this behavior before I saw your question, so I made a test by changing the expected return type.

So the following code :

// I only changed your callback signature from void to string
function greet(name: string): string {
    return `Hello ${name}`;
}
   
function logGreeting(name: string): void {
    console.log(`Hello ${name}`);
}
    
function doSomething(name: string, callbackFn: (name: string) => string /* this is what I changed */) {
    callbackFn(name);
}
    
doSomething('Zion', logGreeting);
doSomething('John', greet);

Will return the following error :

est.ts:13:21 - error TS2345: Argument of type '(name: string) => void' is not assignable to parameter of type '(name: string) => string'.
    Type 'void' is not assignable to type 'string'.
    
    13 doSomething('Zion', logGreeting);
                           ~~~~~~~~~~~
    Found 1 error

So for me this behavior makes sense. Please tell me if my explanation was not clear enough, so that I can try to make it clearer.

In a nutshell, Typescript is not expecting to get a return value; so if your function returns something, Typescript won't throw an error, but you will not be allowed to use it!

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187312

Think of a void return type as meaning that the return value can't be used. It doesn't really matter if it returns something or not, but typescript will not allow to use the return value if it's typed as void.

This allows you to pass pass function that might return a value as a function whose return value is ignored.

Upvotes: 1

Related Questions