TypeScript Optional function in Interface

后端 未结 1 1574
生来不讨喜
生来不讨喜 2020-12-24 00:19

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

interface IElement {
  name: string;
  options: any;
  type: string;
  value?: st         


        
1条回答
  •  隐瞒了意图╮
    2020-12-24 00:34

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

    Using your example of a validation function taking 1 parameter (of any type) and a boolean return value:

    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)

    validation?(flag: any) : boolean;
    

    or in the third syntax (as you found):

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

    0 讨论(0)
提交回复
热议问题