Exit in TypeScript
Here’s an idiomatic TypeScript example demonstrating the concept of exiting a program:
// Exit.ts
// Import the process module to access exit functionality
import * as process from 'process';
// Function to demonstrate deferred execution
function cleanup(): void {
console.log("Cleanup function called");
}
// Main function
function main(): void {
// Register cleanup function
process.on('exit', cleanup);
console.log("Starting the program");
// Exit with status code 3
process.exit(3);
// This line will never be executed
console.log("This will not be printed");
}
// Run the main function
main();
This TypeScript code demonstrates how to exit a program with a specific status code. Let’s break it down:
We import the
process
module, which provides information about, and control over, the current Node.js process.We define a
cleanup
function that simulates a cleanup operation. In a real-world scenario, this might include closing database connections or freeing resources.In the
main
function:- We register the
cleanup
function to be called when the process exits usingprocess.on('exit', cleanup)
. - We use
process.exit(3)
to immediately terminate the program with a status code of 3. - Any code after
process.exit()
will not be executed.
- We register the
Finally, we call the
main
function to run our program.
To run this TypeScript program:
- Save the code in a file named
Exit.ts
. - Compile the TypeScript code to JavaScript:
$ tsc Exit.ts
- Run the compiled JavaScript file:
$ node Exit.js
Starting the program
Cleanup function called
- Check the exit status:
$ echo $?
3
Note that unlike some languages like C, TypeScript (running on Node.js) doesn’t use the return value from the main function to indicate the exit status. Instead, we explicitly use process.exit()
to set the exit code.
This example demonstrates how to handle program termination in TypeScript, including setting exit codes and performing cleanup operations. It’s particularly useful when writing command-line applications or scripts where communicating the program’s final status is important.