Home > Mobile >  Confused about Typescript Function Types
Confused about Typescript Function Types

Time:10-26

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!

CodePudding user response:

Here's is my interpretation of this behavior :

you are 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 it's not intended to be used.

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

i didn't knew this behavior before i saw your question, so i made tests by changing the expected signature according to my example.

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) {
  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. Tell me if my explanation was not clear enough, in this case i'll try to make it clearer.

Conclusion : The main thing is that TS is not expecting to get a return value, so if your function returns something, this is not a problem, but you will not be allowed to use it...

CodePudding user response:

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.

  • Related