How To Define Functions In TypeScript
TypeScript
26/08/2021
Here's a quick rundown on functions in TypeScript. πββοΈ
Parameters
Parameters should always be followed by type annotations. The exception to this rule are default values as TypeScript is able to infer the type from the values themselves. Is a parameter optional? Mark it with a ?
or else your linter will throw an error when calling the function.
TYPESCRIPT
function printName(firstName: string, lastName = 'Smith', middleName?: string) { if (middleName) console.log(firstName, middleName, lastName) else console.log(firstName, lastName) }
Return value
While TypeScript can infer a function's return type, it's good practice π to explicitly state it as it serves as a form of self-documentation. The type annotation is written after the parentheses and before the function body.
If the function doesn't return anything, type void
is used.
TYPESCRIPT
function getNumber(): number { return 6 }function sayHello(): void { console.log('Hello!') }
Arrow functions
In arrow functions, type annotations follow the same syntax as in function declarations.
TYPESCRIPT
const isNumber5 = (value: number): boolean => value === 5