Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  119] [ 2]  / answers: 1 / hits: 78752  / 10 Years ago, wed, december 17, 2014, 12:00:00

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.

}

More From » typescript

 Answers
15

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;

[#68463] Sunday, December 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;