I try to use Spark with TypeScript but when I write this
Spark.get("/facture", (req, res) => {
chalk.red('Hello test');
chalk.green('Hello word');
})
It return me undefined but when I write only 1 line it works
Spark.get("/facture", (req, res) =>
chalk.green('Hello word');
)
I think that the problem come from the syntax. Someone can help me please
When using arrow functions, if they are one liners you can omit the { } and the value returned by the expression will be the return value of the function.
In essence:
Spark.get("/facture", (req, res) =>
chalk.green('Hello word');
)
Transpiles to:
Spark.get("/facture", function (req, res) {
return chalk.green('Hello word');
});
However when you have more than one statement and you make a body for the arrow function you must manually return the value as you would in normal functions.
You can easily see it when transpiled.
Spark.get("/facture", (req, res) => {
chalk.red('Hello test');
chalk.green('Hello word');
})
Transpiles to:
Spark.get("/facture", function (req, res) {
chalk.red('Hello test');
chalk.green('Hello word');
});
If you want to return something you have to write the return statement:
Spark.get("/facture", (req, res) => {
chalk.red('Hello test');
return chalk.green('Hello word');
})
So it ends up like this in javascript:
Spark.get("/facture", function (req, res) {
chalk.red('Hello test');
return chalk.green('Hello word');
});
You can see the examples in the playground here and learn more about arrow functions on the MDN page for them here.