EaGle Network
EaGle Network

Reputation: 103

Typescript function type

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.

Upvotes: 3

Views: 115

Answers (1)

SaroGFX
SaroGFX

Reputation: 909

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
}

Upvotes: 2

Related Questions