接口中的TypeScript可选功能 [英] TypeScript Optional function in Interface
本文介绍了接口中的TypeScript可选功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在TypeScript中使用可选功能创建接口?
Is it possible to create an Interface in TypeScript with optional function?
interface IElement {
name: string;
options: any;
type: string;
value?: string;
validation(any): boolean; // --> should be optional.
}
推荐答案
TypeScript当前允许在接口中进行函数声明的三种语法:
There are currently three syntaxes that TypeScript allows for function declarations in interfaces:
使用带1个参数( any
类型的参数)和 boolean
返回值的 validation
函数示例:
Using your example of a validation
function taking 1 parameter (of any
type) and a boolean
return value:
validation: {(flag: any): boolean};
或采用新的语法:
validation(flag: any) : boolean;
或替代方法是:
validation: (flag: any) => boolean;
解决方案:
因此,使用旧语法使其成为可选内容很容易:
so to make it optional with the old syntax is easy:
validation?: {(flag: any): boolean};
具有第二种语法(最近添加-多亏了 @toothbrush
)
with the second syntax (recent addition - thanks to @toothbrush
)
validation?(flag: any) : boolean;
或使用第三种语法(如您所见):
or in the third syntax (as you found):
validation?: (flag: any) => boolean;
这篇关于接口中的TypeScript可选功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文