Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Optional function in Interface

People also ask

How do you make a field optional in TypeScript interface?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!

How do you make a function optional in TypeScript?

Use a question mark to set an optional parameter in a function in TypeScript, e.g. function sum(a: number, b?: number) {} . If set to optional, the parameter can have a type of undefined or the specified type, because unspecified parameters get the value undefined . Copied!

Can we have interface with optional and default properties in TypeScript?

If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional. Copied!

How do you define a function in interface TypeScript?

TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon. This optional property indicates that objects belonging to the Interface may or may not have to define these properties.


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;