Declaration of functions in Typescript interface depends of the structure of the function itself.
We have a Typescript Interface named MyInterfaceName
where there is a function called myFunction()
. It returns nothing (void), the only type we can use for that case in Typescript is any
. We could think that it’s better to use void
but unfortunately in Typescript never
can also be applied in some cases.
interface MyInterfaceName { something: string myFunction(): any }
We declare the function same as before but we add the argument and it’s type in the Typescript Interface.
interface MyInterfaceName { something: string myFunction(firstArgument: boolean): any }
This time in the function declaration in the Typescript interface, instead of using any
, we put the returned type.
interface MyInterfaceName { something: string myFunction(firstArgument: boolean): string }
To declare an optional function, it’s the same as other variables declared in a Typescript interface, simply put a ?
at the end.
interface MyInterfaceName { something: string myFunction(firstArgument: boolean): string myOptionalFunction?(firstArgument: number): boolean }
You can now declare function in a clean way in Typescript interface !
If you want to use your interface better, check how to change typescript type in a function using type guard