As I delve into the world of TypeScript, I have encountered a few areas where improvements could be made in my understanding. Here is what I have learned so far:
When it comes to augmentation, it seems that utilizing express-serve-static-core
is more effective than using just express
. I struggled to get it to work without incorporating express-serve-static-core
.
In terms of augmenting express
, exporting it back from express-formater
seems to be the way to go based on my exploration. According to TypeScript's documentation, express-formater
acts as a module plugin. I tried following a similar pattern used in moment-range
but couldn't find success.
Take a look at the relevant code snippet below:
express-formater.ts
import core from "express-serve-static-core";
import express from "express";
declare module "express-serve-static-core" {
export interface Response {
respondWith: (p1: any) => Response;
}
}
express.response.respondWith = function(data: string) {
return this.json({
error: null,
data: data
});
};
export default express;
The primary index.ts
file:
import express from "./express-formater";
const app = express();
const port = 8080;
app.get("/", (req, res) => res.respondWith({ ok: true }) );
app.listen(port, () =>
console.log(`Typescript app listening on port ${port}!`)
);
To view the updated version, visit the codesandbox. Make sure your tsconfig.json
has "esModuleInterop": true
set.
UPDATE
I confirmed that exporting express
back from express-formater
is not necessary. A revised approach for future reference:
express-formater.ts
import core from "express-serve-static-core";
import express from "express";
declare module "express-serve-static-core" {
export interface Response {
respondWith: (p1: any) => Response;
}
}
express.response.respondWith = function(data: string) {
return this.json({
error: null,
data: data
});
};
The main index.ts
file:
import express from "express"
import "./express-formater";
const app = express();
const port = 8080;
app.get("/", (req, res) => res.respondWith({ ok: true }) );
app.listen(port, () =>
console.log(`Typescript app listening on port ${port}!`)
);
Check out the updated version on codesandbox.