Javascript 接口中的 TypeScript 可选函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27522973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:15:53  来源:igfitidea点击:

TypeScript Optional function in Interface

javascripttypescript

提问by Anton Selin

Is it possible to create an Interface in TypeScript with optional function?

是否可以在带有可选功能的 TypeScript 中创建接口?

interface IElement {
  name: string;
  options: any;
  type: string;
  value?: string;
  validation(any): boolean; // --> should be optional.

}

回答by Gone Coding

There are currently three syntaxes that TypeScript allows for function declarations in interfaces:

目前 TypeScript 允许在接口中声明函数的三种语法:

Using your example of a validationfunction taking 1 parameter (of anytype) and a booleanreturn value:

使用带有validation1 个参数(any类型)和boolean返回值的函数示例:

validation: {(flag: any): boolean};

or in the newer syntax:

或使用较新的语法:

validation(flag: any) : boolean;

or an alternative is:

或者替代方案是:

validation: (flag: any) => boolean;

Solution:

解决方案:

so to make it optional with the old syntax is easy:

所以用旧的语法使它成为可选的很容易:

validation?: {(flag: any): boolean};

with the second syntax (recent addition - thanks to @toothbrush)

使用第二种语法(最近添加 - 感谢@toothbrush

validation?(flag: any) : boolean;

or in the third syntax (as you found):

或在第三种语法中(如您所见):

validation?: (flag: any) => boolean;