Today you can reuse type annotations for
Variables:
const x:TypeX = {..};
And for classes:
class X implements InterfaceX {}
But not for functions:
type SumType = (a: number, b: number) => number;
function sum(a, b) {
return a + b;
}
Not sure what syntax would be ideal, but the ability to re-use function signatures would be valuable for:
You can try one of these, depending on your needs:
(sum: SumType);
function sum(a, b) {
return a + b;
}
```js
const sum: SumType = function (a, b) {
return a + b;
}
```js
const sum = (function (a, b) {
return a + b;
}: SumType); // useful for callbacks
I don't think you can avoid mentioning the parameters twice (once in the type and again in the function definition) because Babel needs to be able to compile the function definition to JS without knowing anything about types.
@jesseschalken I didn't know about the first option (sum: SumType) - thanks for sharing! It's a bit awkward but is more-or-less what I was looking for, as this keeps the name of the function intact.
@aldendaniels Just keep in mind (sum: SumType); doesn't actually change the type of sum, it only checks that it's compatible with SumType. Eg:
type FooType = () => string|number;
(foo: FooType);
function foo() {
return 1;
}
foo().toFixed(); // Allowed
const x: 1 = foo(); // Allowed
@jesseschalken Thanks for clarifying. So yeah, it seems that the behavior I'm looking for isn't currently supported.
Curious if there's any ongoing discussion on this? I couldn't find any other issues, but having a way to solve this would be great.
For my use-case, I have module A that exports some functions. Those functions get passed to React components as props. Right now I have to manually specify the function types on every component that accepts it as a prop. It would be nice if I could _export_ the type from module A, and use that type in my prop annotations.
Am I missing anything here? Seems like the solution mentioned above is almost there, but I still have to declare the type and annotate the function's arguments.
Most helpful comment
Curious if there's any ongoing discussion on this? I couldn't find any other issues, but having a way to solve this would be great.
For my use-case, I have module
Athat exports some functions. Those functions get passed to React components as props. Right now I have to manually specify the function types on every component that accepts it as a prop. It would be nice if I could _export_ the type from moduleA, and use that type in my prop annotations.Am I missing anything here? Seems like the solution mentioned above is almost there, but I still have to declare the type and annotate the function's arguments.