This situation can be a bit confusing because the use of :
serves two different purposes in the same line: one is for assigning values in a dictionary within JavaScript, and the other is to provide type information in TypeScript.
let someMessageWithoutReturnType = () => { return 'Hello World!'; }
// ^-- lambda function -----------^
let someMessage = (): string => { return 'Hello World!'; }
// ^-type-^
// ^-- lambda function -------------------^
In both examples above, the variable itself does not have type information. Instead, the lambda function includes optional type information with an explicit return type, similar to the standard function syntax shown here in the Functions page of the handbook:
function add(x: number, y: number): number {
return x + y;
}
let myAdd = function(x: number, y: number): number { return x + y; };
The behavior remains the same when assigning inside a dictionary, but the first :
acts as the assignment operator instead of =
, while the second :
specifies the return type for the function expression. This distinction avoids ambiguity since you cannot explicitly assign a type to the key someMessage
in your dictionary using a colon alone; a cast would be required.
let someMessageDict = {
someMessage: (): string => { return 'Hello World!'; }
// ^-- lambda function -------------------^
};
On the other hand, the syntax you referenced pertains to typing the variable, as discussed in the section "Writing the function type". In this case, the variable is explicitly typed without being assigned any value or implementation.
let testMessage: () => string;
class SomeClass {
testMessage: () => string; // defines an unset field
testMessage2: () => string = SOME_FUNCTION_DECLARED_ELSEWHERE;
testMessage3: () => string = (): string => { /* ... */ };
}
The class definition demonstrates where confusion may arise: the :
symbol indicates type information, while =
is used for setting an initial value. Nevertheless, the principle remains consistent: employ =>
for specifying return types in type expressions, and utilize :
for annotating inline function definitions (which may themselves employ =>
syntax) with a return type.