In TypeScript we can specify the data type of the value that a function will return or indicate if no data will be returned:
Typed returns in TypeScript
The return type will be specified after the parentheses containing the function arguments:
- Void: functions with no return
This type of function executes certain instructions, but does not return any data. These are known as void
functions. They are defined as follows:
function printName(yourName: string): void { console.log(`Hello ${yourName}`); }
- Functions with return
On the other hand, if in the function we will return some value, we can specify the data type of it:
function sum(a: number, b: number): number { return a + b; }function helloWorld(): string { return "Hello, World!"; }
Also returns can be more than one data type:
function returnMajor(a: number, b: number): number | string { if(a > b){ return a; } else if( b > a ) { return b; } else { return `The numbers ${a} and ${b} are equal`; } } }
TypeScript also infers this
If we do not indicate in our function declaration the return type, TypeScript, as with variables, can infer it depending on whether you return data (be it string
, number
, etc.) or if nothing is returned ( void
type).
Contributed by: Martín Álvarez.
Want to see more contributions, questions and answers from the community?