How to Add Functions (including useState) to TypeScript Interfaces

I was having trouble finding out how to add functions to TypeScript interfaces. When I finally found out how I decided to write this. I’ll show the format immediatly below:

export default function CardExpirationField({
  setValidCardExpiration,
  setShowCardExpirationError,
  setCardExpirationValue,
  cardExpirationHasBeenBlurred,
}: {
  showCardExpirationError: boolean,
  setValidCardExpiration(arg: boolean): void,
  setShowCardExpirationError(arg: boolean): void,
  setCardExpirationValue(cardExpirationInput: string): void,
  cardExpirationHasBeenBlurred: boolean,
}) {
  return(
    //...
  )
}

We can see that to create a type for a function, we need to use the format functionName(nameForArgument: [argument type]): [type] . We need to write the function name with parentheses directly after. Inside the parentheses, we create a name for any arguments passed to the function (separated by comma), and set the expected types of those arguments. We set a colon “:” after the function name and then write the type of the expected output of the function.

Easy once you know how to do it!

Subscribe to new blog posts