Export default explanation TypeScript

Viewed 196

I am very new to JS, TS, and node in general. I came across https://github.com/santiq/bulletproof-nodejs there is one section of code that I am looking at which I do not understand so I was wondering if anyone can explain part of the code. This project have normal app.ts as entry point, inside it imports express and uses a loader to setup express at https://github.com/santiq/bulletproof-nodejs/blob/master/src/loaders/express.ts

export default ({ app }: { app: express.Application }) => {

What does this export, exports in another word what does { app }: { app: express.Application } mean, why are they in curly braces?

2 Answers

It exports an arrow function that accepts an object with an app property of type express.Application that it plucks the app property out of via destructuring. It doesn't declare a return type so either it doesn't have one or it relies on TypeScript inferring it from the code of the function (which is often just fine to do). It could also be written like this:

const fn = ({ app }: { app: express.Application }) => {
    // ...
};
export default fn;

The export is the default export, meaning you import with default export import syntax:

import anyNameYouLike from "./the-module";

rather than named export import syntax (import { something } from ...).

This exports a function that takes a single argument of type:

{ app: express.Application }

Breaking this down a little, let's declare it as a concrete type:

type ExpressProps = { app: express.Application }

then redeclare the function:

export default ({ app }: ExpressProps) => {

Now... why is the paramater {app} in curlies?

This is an argument destructure and allows us to use app in the function body. Without the destructure, we'd have to:

export default (props: ExpressProps) => { // use props.app
Related