How to implement a method in an interface in TypeScript?
interface Bar
{
num: number;
str: string;
fun?(): void;
}
class Bar
{
fun?()
{
console.log(this.num, this.str);
}
}
let foo: Bar = {num: 2, str: "B"};
foo.fun();
Expected: 2 B
Actual:
Error Cannot invoke an object which is possibly 'undefined'.ts(2722)
If the optional flag is omitted from the method fun(), then the error will be:
Property 'fun' is missing in type '{ num: number; str: string; }' but required in type 'Bar'.ts(2741)
Update 1
This is a work-around that results in what is expected, though it does not seem like the proper way to do this.
if(foo.fun)
{
foo.fun();
}