【问题标题】:Is it possible to include method in TypeScript interface?是否可以在 TypeScript 接口中包含方法?
【发布时间】:2017-11-27 18:01:31
【问题描述】:

只是我在想一个简单的问题,是否可以在接口中包含方法或函数,如下所示:

等待您的 cmets 和关于这样做的可能性或问题的想法:

export interface INewsletter {
  id: number;
  title: string;
  release_date: any;
  filename: string;
  original_filename: string;
  notification: boolean;
  file: File;
  newsletterTranslations: any;
  translations: any;
  newsletterFiles: any;
  newsletter_files: any;

  myMethod() { something to do } // My method here
}

【问题讨论】:

  • @JuanMendes 仅供参考,Java 8 允许您为接口方法提供默认实现,就像他们在这里要求的那样。

标签: typescript


【解决方案1】:

接口是一种契约。您可以指定接口具有方法,但不能包含实现。所以添加myMethod() : void; 是有效的,但不是 myMethod() { something to do } 因为这包括一个实现/主体。

export interface INewsletter {
  id: number;
  title: string;
  release_date: any;
  filename: string;
  original_filename: string;
  notification: boolean;
  file: File;
  newsletterTranslations: any;
  translations: any;
  newsletterFiles: any;
  newsletter_files: any;


  myMethod():void; // replace void with any other return type or any
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2012-10-10
    • 2016-02-26
    • 2021-11-20
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多