Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript function type

Tags:

typescript

I am new to Typescript and was exploring the function type. Please help me understand why the following snippet is not throwing error.

interface Person {
   firstName: string,
   age?: number,
   sayHello(name: string): void 
}

let chethan:Person = {
   firstName: "chethan",
   sayHello: function() {
      return 1;
   }
}

As you can see here, in my interface I have mentioned that sayHello should accept a string and return void. But when I gave a default value to "chethan" obj the sayHello is not accepting string parameter and also returning number instead of void. But Typescript is not throwing any error.

like image 837
EaGle Network Avatar asked May 30 '26 20:05

EaGle Network


1 Answers

This is expected behaviour. Another way to think of this is that a void-returning callback type says "I'm not going to look at your return value, if one exists".

You can find more info on this here: https://github.com/microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void

If you want type safety there to accept only void. You can type it directly on the function in the object.

sayHello: function():void {
   return 1; // should give an error
}
like image 177
SaroGFX Avatar answered Jun 02 '26 20:06

SaroGFX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!