(It's in the title of the question)
I could see a lot of different ways to write a function in Typescript, for instance :
Ex 1
function buildName(firstName: string, lastName: string) {
return firstName + " " + lastName;
}
but also,
Ex2
function buildName(firstName: string, lastName: string): string {
return firstName + " " + lastName;
}
I couldn't really figure out why if what comes after "function(params):" is a type, why isn't it always present. For example, in Java or C++, a function always tells what type of stuff it returns. When the function returns nothing, this is still indicated in these languages as void
.
Typescript's ": type" after function parameters is there to tell of what type is the stuff return by the function like in Java or C++. However, Typescript by default infers the return type of the function so that it's not always necessary to explicitly write it in the code.
In Ex1 the function buildName
returns firstName + " " + lastName
which is composed of strings
. Hence the compiler knows that the function returns a string
.
In Ex2 the function buildName
has : string
after it's parameters. This means that the programmer explicitely tells that the function returns a string
. This can be helpful as the compiler will check that what's returned by the function is really a string
or not. If it's not, it will throw an error which can tell the programmer that he did a mistake since the function is not behaving as expected.
Here are some good resources I used to learn functions in Typescript:
Typescript Handbook: functions - The official handbook for typescript.
Typing functions in TypeScript | 2ality - A long but rather complete a well-illustrated guide on typescript's function.
NB : There are similar questions on StackOverflow but not matching what I searched. I decided to do my own.