How to define the type of a named function?

Viewed 3261
function Foo(): string {}

Means a Foo is a function that returns a string.

interface SFC {
    (props: Props): any;
}

const Foo: SFC = p => {};

Means that Foo is an anonymous function matching the signature SFC and p is of type Props.

How can I declare function Foo() that matches SFC? What's the syntax?

i.e., I want to declare a function using the function keyword (not const) and the function itself is of type SFC.


These don't work:

function Foo: SFC () {}
function Foo() {}: SFC
3 Answers

There are a number of TypeScript proposals for explicitly typing a function declared as a named, hoisted function (as opposed to an expression). None of them have been implemented yet. #22063 seems to be the most active.

  • #16918: (Proposal) syntax for contextual typing of a function declaration
  • #22063: Suggestion: Type annotations and interfaces for function declarations
    • Dupe #37433: Add mechanism for specifying the type of a function declaration
    • Dupe #39419: Allow function declarations to be typed
    • Dupe #40455: Provide a way to indicate that a function declaration conforms to some interface/type
  • #34319: Describe function signature using an interface
    • Dupe #39039: A syntax for function declarations to "implement" types (like const C: React.FC<Props> = (props0) => ...)
  • #40378: Type Cast or Assertions on the FunctionDeclaration

The anticipated release of the satisfies keyword in TypeScript 4.9 (#47920, #46827) is related, but only applies to expressions. It does not change function definitions.

Related