typescriptsyntax

How to define the type of a named function?


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

Solution

  • 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.

    The release of the satisfies keyword in TypeScript 4.9 (#47920, #46827) is related, but only applies to expressions; it does not change function definitions. Open issue #51556 claims to follow up on #47920 with satisfies on functions, with #52195 duped against it.

    Related SO questions: