185

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.

}
1
  • 2
    I found an answer, i think there is possible to implement optional function like this: validation?: (any) => boolean; Commented Dec 17, 2014 at 10:16

2 Answers 2

327

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;
Sign up to request clarification or add additional context in comments.

5 Comments

The way you've written it, any is not a type, but is the name of a parameter that is implicitly of type any. Parameters must be named, even on interfaces. This code will fail to compile if --noImplicitAny is enabled. It should be something like this: validation?:(whatever:any) => boolean; where whatever is some reasonable parameter name.
@NYCdotNet: Yes, I should not have taken the original as-read. Corrected :)
@gone-coding Hi! How do I know if the function is defined or not?
@IlanOlkies: Same way you test for anything in JavaScript if (object.validation) :) It needs to against the object context, so if (this.validation) may also be appropriate depending on your circumstance.
thank you! found this very helpful for optional function props and TS errors :)
6

Just like field properties, we can also declare optional methods in an interface, just by placing "?" after the method name

 interface Vehicle{
  run?(): void;
}

class Sedan implements Vehicle {}

class SUV implements Vehicle {
  run() {
    console.log("run run");
  }
}

let suv = new SUV();

suv.run();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.