HomeContact
Typescript
How to declare functions in Typescript interface.
March 25, 2021
1 min

Declaration of functions in Typescript interface depends of the structure of the function itself.

Function that does not take arguments and does not return a value

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
}

Function that accepts an argument

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
}

Function that accepts an argument and returns a value

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
}

Optional Function

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


Tags

javascripttypescript

Related Posts

Difference between void and never in Typescript.
March 29, 2021
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media