TypeScript Hello World

TypeScript is a powerful, typed superset of JavaScript that compiles to plain JavaScript. It adds static typing and other features to JavaScript, making catching errors early and building more maintainable applications easier. This guide will walk you through creating your first TypeScript program: the classic “Hello, World!” example.

typescript hello world

Writing the TypeScript Code for Hello World

Create a TypeScript File

Inside your project directory, create a new file named hello.ts:

Write the “Hello, World!” Program

Open hello.ts in your code editor and add the following code:

TypeScript ‘Hello World’ Code Explanation:

  1. const greeting: string: Declares a constant variable greeting with a type annotation string.
  2. console.log(greeting): Prints the value of greeting to the console.

Compiling TypeScript to JavaScript

TypeScript files (.ts) cannot run directly in the browser or Node.js. You need to compile them into JavaScript files (.js).

Compile the TypeScript File

Run the following command to compile hello.ts:

This will generate a hello.js file in the same directory. If Typescript is not setup in your system refer to this tutorial guide – Setting Up TypeScript and Running Code

Run the JavaScript File

Execute the compiled JavaScript file using Node.js:

You should see the output:

Automating the Process (Optional)

You can set up a TypeScript configuration file and watch mode to streamline development.

Create a tsconfig.json File

Run the following command to initialize a TypeScript configuration file:

This generates a tsconfig.json file. Open it and modify the following options:

Explanation:

  • outDir: Specifies the directory for compiled JavaScript files.
  • strict: Enables strict type-checking.
  • include: Specifies the files to compile (all .ts files inside the src directory).

Update Project Structure

Reorganize your project as follows:

Compile and Watch for Changes

Run TypeScript in watch mode:

This will automatically compile your files whenever you make changes.

Adding TypeScript to a Web Page (Optional)

To include your TypeScript code in a web page:

  1. Create an index.html file in your project:
  1. Open index.html in a browser, and check the console to see Hello, World!.

Conclusion

Congratulations! You’ve successfully written, compiled, and executed your first TypeScript program. TypeScript’s static typing and advanced features provide a robust foundation for building modern JavaScript applications. Continue exploring to unlock its full potential!

See Also

1 thought on “TypeScript Hello World”

Leave a Comment