【发布时间】:2020-04-06 09:36:22
【问题描述】:
如何在 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
实际:
ErrorCannot 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();
}
【问题讨论】:
标签: typescript methods interface