Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 492
mpen Avatar asked Aug 03 '17 00:08

mpen


People also ask

How do you define a named function?

Named Functions: In JavaScript, named functions are simply a way of referring to a function that employs the function keyword followed by a name that can be used as a callback to that function. Normal functions with a name or identifier are known as named functions.

How do you define a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)


1 Answers

TypeScript uses duck typing, so the Foo function is of type SFC if their structure matches.

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

function Foo(props: any): any {
    console.log(props);
}

let sfc: SFC = Foo; // Foo is of type SFC.
sfc("Foo");
like image 61
Rodris Avatar answered Sep 18 '22 17:09

Rodris