TypeScript helps catch mistakes early by checking your code before running it. It adds clear rules about the types of data you use, making your code easier to understand and fix.
0
0
Why TypeScript over JavaScript
Introduction
When building bigger projects where many people work together.
When you want to avoid bugs caused by wrong data types.
When you want your code to be easier to read and maintain.
When you want helpful hints and errors while writing code.
When you want to use new JavaScript features safely.
Syntax
Typescript
TypeScript code looks like JavaScript but adds types like: let age: number = 25; let name: string = "Alice"; function greet(person: string): string { return `Hello, ${person}!`; }
TypeScript files usually end with .ts instead of .js.
TypeScript needs to be converted (compiled) to JavaScript before running in browsers.
Examples
This shows how TypeScript prevents assigning wrong types.
Typescript
let count: number = 10; count = 20; // OK // count = "twenty"; // Error: Type 'string' is not assignable to type 'number'.
Functions can specify types for inputs and outputs.
Typescript
function add(a: number, b: number): number { return a + b; } let result = add(5, 3); // result is 8
Interfaces define the shape of objects for clearer code.
Typescript
interface Person {
name: string;
age: number;
}
let user: Person = { name: "Bob", age: 30 };Sample Program
This simple program shows how TypeScript uses types to make sure the function gets a string and returns a string.
Typescript
function greet(name: string): string { return `Hello, ${name}!`; } console.log(greet("Alice"));
OutputSuccess
Important Notes
TypeScript helps find errors before running your code, saving time.
You can gradually add TypeScript to existing JavaScript projects.
Using TypeScript can improve your coding skills by making you think about data types.
Summary
TypeScript adds types to JavaScript to catch errors early.
It makes code easier to read, maintain, and work on with others.
TypeScript code needs to be converted to JavaScript to run in browsers.