【问题标题】:TypeScript: interface method implementationTypeScript:接口方法实现
【发布时间】: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


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

      Typescript 告诉你它是未定义的,因为你没有提供在这一行中调用的方法:

      let foo: Bar = {num: 2, str: "B"};
      

      试试

      const myTestFun = () => {
        console.log('I am here!')
      }
      let foo: Bar = {num: 2, str: "B", fun: myTestFun };
      

      【讨论】:

        猜你喜欢
        • 2019-05-09
        • 1970-01-01
        • 2017-11-06
        • 2019-01-14
        • 1970-01-01
        • 2016-06-20
        • 2020-06-04
        • 2014-10-10
        • 2022-01-22
        相关资源
        最近更新 更多