Issue
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.
- #16918: (Proposal) syntax for contextual typing of a function declaration
- #22063: Suggestion: Type annotations and interfaces for function declarations
- #34319: Describe function signature using an interface
- Dupe #39039: A syntax for function declarations to "implement" types (like
const C: React.FC<Props> = (props0) => ...
)
- Dupe #39039: A syntax for function declarations to "implement" types (like
- #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.
Answered By - Jeff Bowman Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.