3
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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

6 Comments

f1 and f2 are equivalent, if you look at the infered typed it is both () => number
no. the result may be equivalent, however this does not mean that they both represent the same thing. the empty object literal is just a special condition that by "accident" resolves to the same result as f2. If you want to define a function as return value f2 is the way to go, since it is completely clear, no chance to misunderstand it.
I agree that you should define it like f2 if you want a function, but in this particular case, f1 andf2 are equivalent and therefore, represent the same thing. It is not just an object literal, you can effectively define functions with other properties using this notation, look at @tao's answer.
I understand your point :D in @tao's answer the type has to be an object with the specified return values so, e.g. {x: (param: number): void => {}, bar: 'test'} but still i think they have a different intention. If I have to verify/read your code I assume that for f1 you want to declare an object as type, and for f2 a function
Yeah, you should never define it like f1 if you want to have the type () => number :-)
|
-3

Yes you can specify the return type of functions.

let f1 = function (): boolean {}

1 Comment

he asked for the variable return type. in your case you just declared the return type for a random function that is assigned to f1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.