3

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.

1

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.