如何在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)
这是一种解决方法,可以达到预期的效果,尽管这似乎不是执行此操作的正确方法。
if(foo.fun)
{
foo.fun();
}
答案 0 :(得分:1)
Typescript告诉您它是未定义的,因为您没有提供在此行中调用的方法:
let foo: Bar = {num: 2, str: "B"};
尝试
const myTestFun = () => {
console.log('I am here!')
}
let foo: Bar = {num: 2, str: "B", fun: myTestFun };
答案 1 :(得分:1)
在要创建的类中实现接口,然后调用。
interface BarInterface
{
num: number;
str: string;
fun: () => void;
}
class Bar implements BarInterface {
num: number;
str: string;
constructor(num: number, str: string) {
this.num = num;
this.str = str;
}
fun() {
console.log(this.num, this.str);
}
}
let foo = new Bar(2, "B");
foo.fun();