Let's focus solely on the initial line.
getTodos(): Todo[] {
This snippet defines a function called getTodos
and specifies its return type as Todo[]
.
The opening curly brace signals the beginning of the function's implementation.
By declaring the return type, the compiler can flag any discrepancies where the function does not adhere to this specified type. This proactive error prevention is one of TypeScript's strengths.
You may be curious about the function type when it doesn't yield anything in return (using 'void' or an empty return statement).
doStuff() : void {
// I dont return anything*.
}
Consider a scenario where we want to remove the last element from an array and return that removed element. The method could be defined like so:
removeLastElementOfArray(array: any[]): any {
return array.pop();
}
While it seems intuitive that this function would return a number when given an array of numbers, using 'any' for the return type disconnects the relationship between the array elements and the output type. This is where generics come into play:
removeLastElementOfArray<T>(array: T[]): T {
return array.pop();
}
Now, by utilizing generics, TypeScript understands that passing an array of strings will result in the function returning a string, establishing strong typing relationships. Utilize generics extensively to avoid the use of 'any' whenever possible.
*Note: In JavaScript, functions without explicit return statements default to 'undefined'. However, for clarity and consistency with typed languages, we specify these types with 'void'.