TypeScript Optional function in Interface

JavascriptTypescript

Javascript Problem Overview


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.

}

Javascript Solutions


Solution 1 - Javascript

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnton SelinView Question on Stackoverflow
Solution 1 - JavascriptGone CodingView Answer on Stackoverflow