如何在 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();
预期的:2 B
实际的:
Error Cannot invoke an object which is possibly 'undefined'.ts(2722)
如果方法中省略了可选标志fun(),则错误将是:
Property 'fun' is missing in type '{ num: number; str: string; }' but required in type 'Bar'.ts(2741)
更新 1
这是一种解决方法,可以产生预期的结果,尽管它似乎不是执行此操作的正确方法。
if(foo.fun)
{
foo.fun();
}