TypeScript extends JavaScript and uses the .ts file extension. A typical file includes import statements, type annotations, interfaces, classes, and functions.
You can declare variables with let, const, or var. Always preferlet and const for block scoping. Type annotations can be included:
let count: number = 10;
const username: string = "Alice";
function greet(name?: string): void {
if (name) {
console.log("Hello, " + name);
} else {
console.log("Hello, Guest");
}
}Functions can define the types of their parameters and return values. Parameters can be optional using?:
function add(a: number, b: number): number {
return a + b;
}
const logMessage = (message: string): void => {
console.log(message);
}Type annotations let you declare expected types for variables, function parameters, and return values:
let isActive: boolean = true;
let score: number = 100;
let tags: string[] = ["code", "typescript"];Use // for single-line and /* ... */ for multi-line comments:
// This is a single-line comment
/* This is
a multi-line comment */TypeScript code must be compiled into JavaScript using the TypeScript Compiler (tsc). This makes it runnable in any browser or JavaScript environment.
tsc script.tsAsk the AI if you need help understanding or want to dive deeper in any topic