【问题标题】:Typescript - Object is possibly 'undefined' in interface打字稿 - 接口中的对象可能是“未定义的”
【发布时间】:2021-08-24 00:35:05
【问题描述】:

在 Angular 项目中,我使用的是接口。

    export interface School {
      name: string = '';
      website: string;
      registrationNumber: string;
      dateEstablished: Date;
      address: string;
      country: [];
      companyLogo: any = '';
    
        clear() {
          this.name = '';
          this.website = '';
          this.registrationNumber = '';
          this.dateEstablished = null;
          this.address = '';
          this.country = [];
          this.companyLogo = '';
      }
    }

我有两个错误:

  1. 对象可能是“未定义的”——以及所有的“这个”。突出显示

  2. 预期的声明或声明.ts(1128) - 最后一个右大括号突出显示。

  3. 预期的呼叫签名:'clear' 有一个 typedef (typedef)tslint(typedef)

我如何解决这些问题?

谢谢

【问题讨论】:

  • 我可能弄错了,但我不认为接口可以包含方法实现。接口描述了接口的具体实现中应该存在的成员。它们不包含它们的定义。您是否看到了相反的信息?
  • @JLRishe - 最好的方法是什么。请指教

标签: angular


【解决方案1】:

你需要一个这样的接口实现:

文件:school.ts

interface ISchool {
      name: string = '';
      website: string;
      registrationNumber: string;
      dateEstablished: Date;
      address: string;
      country: [];
      companyLogo: any = '';
    
      clear(): () => void; 

    }


export class School implements ISchool {

      // Declare all attributes here;
      public name: string = '';
      ...

      clear() {
          this.name = '';
          this.website = '';
          this.registrationNumber = '';
          this.dateEstablished = null;
          this.address = '';
          this.country = [];
          this.companyLogo = '';
      }

}

文件 app.ts

import {School} from 'school.ts';

const someSchool = new School();
someSchool.clear();

这是一项基本的面向对象技术,因此我建议您查看类和接口的使用情况。

如果你只有一种学校,你不需要界面。

【讨论】:

  • 我使用的是两 (2) 个导出中的哪一个?类还是接口?
  • 你必须实例化类学校的一个对象,比如 const someSchool = new School();然后调用 someSchool.clear();
  • 对不起,我不明白。可以更新代码吗?
猜你喜欢
  • 2019-09-15
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 2021-01-19
  • 2019-12-24
  • 1970-01-01
  • 2021-08-06
  • 2019-06-12
相关资源
最近更新 更多