Reputation: 18923
let f1: {(): number}
let f2: () => number
let f3: {() => number} // error TS1005: ':' expected.
It looks like f1
and f2
declarations are equivalent, is it true?
And why f3
is an error?
Upvotes: 3
Views: 640
Reputation: 3253
They are not equivalent.
The syntax of f1 usually defines an object literal. Even though in that specific case if you only have one call signature and no properties you can (and should) omit the { } braces to avoid confusion.
If your return type should be a function, f2 is definitely the way to go.
In an object literal you can specify keys and return values, e.g.:
let f4: {test: string, testFn: () => number};
With that example in mind I think it is clear why f3 is invalid.
Upvotes: 1
Reputation: 2242
The notation with the braces allows you to define overload method signatures and/or hybrid types, for example
interface Foo {
(x: number): void,
(x: string): void,
bar: string,
}
has two call signatures and one property bar
.
If you only have one call signature and no properties you can use the shorthand syntax you used for f2
. So with the braces you have to separate the arguments from the return type with :
and in the shorthand syntax with =>
.
Upvotes: 3
Reputation: 736
Yes you can specify the return type of functions.
let f1 = function (): boolean {}
Upvotes: -3