- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
TypeScript First Program
Starting your journey with TypeScript is an exciting step toward writing more reliable and maintainable code. Because browsers and runtime environments like Node.js cannot execute TypeScript directly, the process involves a step called transpilation. This is where your TypeScript code is converted into standard JavaScript. In this guide, we will walk through writing, compiling, and executing your very first TypeScript application.
Steps to Create a TypeScript Program
1. Create a TypeScript File
The first thing to notice is the file extension. While JavaScript uses .js, TypeScript files use the .ts extension. Create a file named hello.ts and enter the following code:
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message: string = greet("TypeScript");
console.log(message);
: string after the parentheses). This makes it immediately clear to other developers what the function is expected to produce.
2. Compile the TypeScript File
To turn this code into something a computer can run, we use the TypeScript Compiler (tsc). Open your terminal or command prompt in the folder where you saved your file and run:
tsc hello.ts
If there are no errors in your code, this command won't show a success message; instead, it will silently generate a new file in your directory named hello.js.
.ts file directly with Node.js (e.g., node hello.ts). This will result in an error because Node.js doesn't natively understand TypeScript's type annotations.
3. Run the Compiled JavaScript
Now that you have a standard JavaScript file, you can execute it using the Node.js runtime:
node hello.js
Output:
Hello, TypeScript!
.ts file, you must run the tsc command again to update the .js file. Otherwise, you will still be running the old version of your code.
Code Explanation
Let's break down exactly what makes this TypeScript code different from standard JavaScript:
- Type Annotation (
name: string): We are explicitly telling TypeScript that thenameparameter must be a string. If you tried to pass a number or an object here, the compiler would stop you before you even ran the code. - Return Type (
: string): After the function parentheses, we specify that this function must return a string. This prevents accidental returns ofnullorundefined. - Template Literals: We use backticks (`) and
${}to inject our variable directly into the string. This is a modern JavaScript feature that TypeScript supports fully. - Type Safety in Action: In a real-world scenario, if you accidentally wrote
greet(42), TypeScript would highlight this as an error in your editor immediately, saving you from a potential logic bug.
Real-World Example
Imagine you are building a user profile page. Without TypeScript, you might accidentally try to display a user's ID instead of their name. With TypeScript, you can define exactly what a "User" looks like:
interface User {
id: number;
username: string;
}
function displayUser(user: User) {
console.log(`User: ${user.username}`);
}
// TypeScript ensures the object matches the interface
displayUser({ id: 1, username: "Alice" });
Summary
Your first TypeScript program highlights the core workflow of modern web development: writing expressive, typed code and compiling it into compatible JavaScript. By using type annotations, you’ve added a layer of documentation and error-checking that makes your programs more predictable and easier to debug as they grow in size.
tsc hello.ts --watch. This tells the compiler to automatically re-compile your file every time you press "Save."