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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With