devmeetings-react-ts-fork
  • Devmeeting React + Typescript
  • Speed dating
  • Typescript
    • It's just JavaScript
    • Basic types
    • Typing objects
    • Typing functions
    • Modules
    • Generics
    • Tasks
  • Hello React
    • Quick look around
    • The first component
    • JSX
    • Tasks
  • Components & Props
    • Small components
    • Passing data to a component
    • Loops in JSX
    • Tasks
  • Stateful components
    • Handling events
    • Components with internal state
    • Talking to a parent component
    • Smart and dumb components
    • Before the break
    • Tasks
  • Side-effects and context
    • Side-effects
    • Prop drilling
    • Using context
    • Tasks
  • What's next
    • Styling
    • Learning component's lifecycle
    • State Management
Powered by GitBook
On this page
  • Reusable function type
  • The void type
  • Optional and default arguments
  • Resources

Was this helpful?

  1. Typescript

Typing functions

When declaring a function we can type both the arguments and the return value:

function multiply(a: number, b: number): number {
    return a * b;
}

Reusable function type

Let's say the above function implements a very common pattern in out app: do some calculation with two numbers.

function sum(a: number, b: number): number {
    return a + b;
}

function modulo(a: number, b: number): number {
    return a % b;
}

We can create a function type:

type BinaryOperator = (a: number, b: number) => number;
const subtract: BinaryOperator = (a, b) => a - b;

The void type

One type is particularly useful with functions is void: to signify that nothing will be returned from the function:

function log(message): void {
    console.log(message);
}

Optional and default arguments

Function arguments can be marked as optional using the ? sign

function done(error?: Error): void {
    /* ... */
}

We can also provide a default value; any argument with a default value will automatically be marked as optional.

function complete(success: boolean = true): void {
    /* ... */
}

Resources

PreviousTyping objectsNextModules

Last updated 5 years ago

Was this helpful?

Handbook: Functions