TypeScript is a superset of JavaScript with an additional layer TypeScript’s type system
Advantages:
Note: JS only provides string and number datatype
let name: string = "Alice";
let isActive: boolean = true;
let randomValue: any = 42; // Can also be a string, object, etc.
let numbers: number[] = [1, 2, 3];
let person: [string, number] = ["Bob", 25];
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
function add(x: number, y: number): number {
return x + y;
}
function greet(name: string, age?: number): string {
return `Hello, ${name}!`;
}
interface User {
name: string;
age: number;
}
const user: User = {
name: "Alice",
age: 30
};
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks.`);
}
}
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello");
let someValue: any = "This is a string";
let strLength: number = (someValue as string).length;
export class Car {
// class implementation
}
import { Car } from './Car';
function log(value: string | number): void {
console.log(value);
}
interface Employee { employeeId: number; }
type EmployeePerson = Person & Employee;
## Decorators
function Log(target: any, propertyName: string, descriptor: PropertyDescriptor) {
console.log(Logging ${propertyName}
);
}
class Example { @Log method() { // method implementation } } ```