Functions in typescript
FUNCTIONS IN TYPESCRIPT
TypeScript lets you write type-safe functions.
This post will show how to write functions, specify
parameters and return types, and define function Signatures.
PARAMETER TYPES
- In TypeScript, we can specify the type for each parameter
- The TypeScript compiler will error if we attempt to pass an incorrect type to a function
- The syntax for defining types for function parameters is simple, just a colon colon “:” and name of the type.
Like JavaScript, you can also use the arrow syntax to define functions.
const joinStrings =
(str1: string, str2: string) => {
return str1 + str2;
}
RETURN TYPE
- Typescript can often infer a function’s return type based on the code inside the function, so it’s common not to specify them explicitly.
- To specify the function return type, we add a colon and the type right after the parameter list, before the function body.
If there is no return type, your function can specify a ‘void” return type
function add
(x: number, y: number): number {
return x + y;
}
const logAdd =
(x: number, y: number) : void => {
console. log(x + y);
}
OPTIONAL PARAMETERS
We can indicate that parameters are optional by adding a question mark.
Optional parameters will appear as an ‘undefined’ type if not specified.
function fullName
(first:string, last : string, middle? : string) {
if (typeof middle == ‘undefined’) {
return ‘${first} ${last}’;
}
else {
return ‘${first} ${middle} ${last}’ ;
}
}
DECLARING FUNCTION SIGNATURES
Functions are a first-class property in TypeScript and can also be defined as types. Imagine a function addNumber that looks like this.
const add =
(a: number, b: number): number => {
return a + b;
}
This function shape or ‘signature’ can be defined as a type…
which allows functions to be passed as a parameter and type- checked
type Add FunctionType =
(a: number, b: number) => number;
const logAdd =
(add Function : AddFunctionType): void => {
console. log( add Function ( 1, 2));
logAdd( (a: number, b: number) => {
return a+ b;
});