Example: Basic TypeScript variable declaration and function:
// Declare a variable with a type
let greeting: string = 'Hello, TypeScript!';
console.log(greeting);
// Simple function with typed parameters
function addNumbers(a: number, b: number): number {
return a + b;
}
console.log(addNumbers(5, 10));
let age: number = 25;
console.log(age);
let name: string = 'Alice';
console.log(name.length);
function square(n: number): number {
return n * n;
}
console.log(square(5));
let fruits: string[] = ['Apple', 'Banana', 'Cherry'];
fruits.forEach(fruit => console.log(fruit));
let person: [string, number] = ['Bob', 30];
console.log(person);
enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday}
console.log(Weekday.Tuesday);
interface Person {name: string; age: number;}
let john: Person = {name: 'John', age: 40};
console.log(john);
function greet(message: string, name?: string) {
console.log(`${message} ${name || 'Guest'}`);
}
greet('Hello');
greet('Hello', 'Alice');
function multiply(a: number, b: number = 2): number {
return a * b;
}
console.log(multiply(5));
console.log(multiply(5, 3));
let value: string | number;
value = 'Hello';
console.log(value);
value = 42;
console.log(value);
function logMessage(msg: string): void {
console.log(msg);
}
logMessage('This is a void function');
type Car = {make: string; model: string; year: number;};
let myCar: Car = {make: 'Toyota', model: 'Corolla', year: 2021};
console.log(myCar);
function sumNumbers(...nums: number[]): number {
return nums.reduce((acc, curr) => acc + curr, 0);
}
console.log(sumNumbers(1,2,3,4));
let someValue: any = 'Hello TypeScript';
let strLength: number = (someValue as string).length;
console.log(strLength);
let numbers: number[] = [5, 10, 3, 8];
let maxNumber: number = Math.max(...numbers);
console.log(maxNumber);
let mySet: Set= new Set([1,2,3]); mySet.add(4); mySet.delete(2); console.log(mySet);
let myMap: Map= new Map([['a',1], ['b',2]]); myMap.forEach((value, key) => console.log(`${key}: ${value}`));
class PersonClass {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person1 = new PersonClass('Alice', 30);
person1.greet();
class Employee extends PersonClass {
position: string;
constructor(name: string, age: number, position: string) {
super(name, age);
this.position = position;
}
showPosition() {
console.log(`${this.name} works as ${this.position}`);
}
}
let emp = new Employee('Bob', 28, 'Developer');
emp.greet();
emp.showPosition();
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log('Woof!');
}
}
let dog = new Dog('Buddy');
dog.makeSound();
function identity(arg: T): T { return arg; } console.log(identity (5)); console.log(identity ('Hello'));
let employees: [string, number][] = [['Alice', 30], ['Bob', 28]];
employees.forEach(([name, age]) => console.log(`${name} is ${age} years old`));
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person;
let key: PersonKeys = 'name';
console.log(key);
let input = document.getElementById('myInput') as HTMLInputElement;
input.value = 'Hello TypeScript';
console.log(input.value);
let user: { name?: { first: string; last: string } } = {};
console.log(user.name?.first);
let inputValue: string | null = null;
let value = inputValue ?? 'default';
console.log(value);
function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
await wait(1000);
console.log('Done after 1 second');
}
run();
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { add } from './mathUtils';
console.log(add(5, 3));
class Car {
readonly brand: string;
constructor(brand: string) {
this.brand = brand;
}
}
let car = new Car('Toyota');
console.log(car.brand);
// car.brand = 'Honda'; // Error
type ID = string | number;
let userId: ID = 'abc123';
let anotherId: ID = 456;
console.log(userId, anotherId);
type StringOrNumber = string | number;
let value: StringOrNumber = 'Hello';
if (typeof value === 'string') {
console.log('It is a string');
}
let fruits: readonly string[] = ['Apple', 'Banana'];
console.log(fruits);
// fruits.push('Orange'); // Error
enum Direction { Up, Down, Left, Right }
for (let dir in Direction) {
console.log(dir);
}
let p = new Promise((resolve, reject) => { setTimeout(() => resolve(42), 1000); }); p.then(value => console.log(value)).catch(err => console.error(err));
interface Vehicle {
brand: string;
wheels?: number;
}
let bike: Vehicle = { brand: 'Honda' };
console.log(bike.wheels); // undefined
type A = { name: string };
type B = { age: number };
type C = A & B;
let person: C = { name: 'Alice', age: 30 };
console.log(person);
function isString(value: any): value is string {
return typeof value === 'string';
}
let val: string | number = 'Hello';
if (isString(val)) console.log('It is a string');
type Size = 'small' | 'medium' | 'large';
let shirt: Size = 'medium';
console.log(shirt);
interface Box{ contents: T; } let box: Box = { contents: 100 }; console.log(box.contents);
type User = [string, number];
let user: User = ['Alice', 25];
let [name, age] = user;
console.log(`${name} is ${age} years old`);
function greet(name: string, greeting?: string) {
console.log(`${greeting || 'Hello'}, ${name}`);
}
greet('Alice');
greet('Bob', 'Hi');
function multiply(a: number, b: number = 2) {
return a * b;
}
console.log(multiply(5)); // 10
console.log(multiply(5, 3)); // 15
function sum(...numbers: number[]) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1,2,3,4,5));
class MathUtils {
static PI = 3.14;
static square(x: number) {
return x * x;
}
}
console.log(MathUtils.PI);
console.log(MathUtils.square(5));
function getProperty(obj: T, key: K) { return obj[key]; } let person = { name: 'Alice', age: 25 }; console.log(getProperty(person, 'name'));
type ReadOnly= { readonly [K in keyof T]: T[K] }; interface Person { name: string; age: number } let p: ReadOnly = { name: 'Bob', age: 30 }; console.log(p);
type Check= T extends string ? 'String' : 'Other'; type Result = Check ; console.log('Result type is', Result);
interface User { name: string; age: number }
let user: Partial = { name: 'Alice' };
console.log(user);
interface Config { host?: string; port?: number }
let cfg: Required = { host: 'localhost', port: 8080 };
console.log(cfg);
interface Point { x: number; y: number }
let p: Readonly = { x: 10, y: 20 };
console.log(p);
interface Person { name: string; age: number; city: string }
type NameCity = Pick;
let pc: NameCity = { name: 'Alice', city: 'Paris' };
console.log(pc);
interface Person { name: string; age: number; city: string }
type WithoutCity = Omit;
let person: WithoutCity = { name: 'Alice', age: 30 };
console.log(person);
type PageInfo = { title: string };
type Page = 'home' | 'about' | 'contact';
const pages: Record = {
home: { title: 'Home Page' },
about: { title: 'About Page' },
contact: { title: 'Contact Page' }
};
console.log(pages);
enum Direction { Up, Down, Left, Right }
let dir: Direction = Direction.Up;
console.log(dir); // 0
type NameAge = [string, number?];
let person: NameAge = ['Alice'];
console.log(person);
interface Person { name: string; age: number }
interface Employee { employeeId: number }
type Staff = Person & Employee;
let staff: Staff = { name: 'Bob', age: 25, employeeId: 123 };
console.log(staff);
type ID = string | number;
let userId: ID = 101;
userId = 'abc123';
console.log(userId);
let someValue: unknown = 'Hello World';
let strLength: number = (someValue as string).length;
console.log(strLength);
type AddFunc = (a: number, b: number) => number;
let add: AddFunc = (x, y) => x + y;
console.log(add(5, 3));
interface User { name: string; address?: { city: string } }
let user: User = { name: 'Alice' };
console.log(user.address?.city);
let value: string | null = null;
let result = value ?? 'Default Value';
console.log(result);
let str: string | null = 'Hello';
console.log(str!.length);
type Sizes = 'small' | 'medium' | 'large';
type CssClass = `${Sizes}-button`;
let myClass: CssClass = 'medium-button';
console.log(myClass);
interface Person { name: string; age: number }
type PersonKeys = keyof Person;
let key: PersonKeys = 'name';
console.log(key);
let value: unknown = 10;
if (typeof value === 'number') {
console.log(value + 5);
}
function error(message: string): never {
throw new Error(message);
}
// error('Something went wrong');
type Func = (...args: unknown[]) => void;
let log: Func = (...args) => console.log(...args);
log('Hello', 123);
type Check= T extends string ? 'Yes' : 'No'; type Result = Check ; console.log('Result is', Result);
type ReturnType= T extends (...args: any[]) => infer R ? R : any; function fn() { return 42; } type R = ReturnType ; console.log(R);
function isNumber(value: any): value is number {
return typeof value === 'number';
}
let x: any = 10;
if (isNumber(x)) {
console.log(x + 5);
}
let arr: unknown[] = [1, 'two', true];
arr.forEach(item => console.log(item));
function identity(arg: T): T { return arg; } console.log(identity('Hello')); console.log(identity(123));
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4));
type Point = [number, number];
let p: Point = [10, 20];
console.log(p);
interface Person { readonly name: string; age: number }
let person: Person = { name: 'Alice', age: 25 };
// person.name = 'Bob'; // Error
console.log(person);
let arr: ReadonlyArray= [1, 2, 3]; // arr.push(4); // Error console.log(arr);
interface Person { name: string; age?: number }
let p: Person = { name: 'Bob' };
console.log(p);
function greet(name: string = 'Guest') {
console.log(`Hello, ${name}`);
}
greet();
greet('Alice');
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any { return a + b; }
console.log(add(2, 3));
console.log(add('Hello', 'World'));
type Point = readonly [number, number];
let pt: Point = [10, 20];
// pt[0] = 5; // Error
console.log(pt);
function getProp(obj: T, key: K) { return obj[key]; } console.log(getProp({ name: 'Alice', age: 30 }, 'age'));
type T1 = 'a' | 'b' | 'c'; type T2 = 'a' | 'c'; type T3 = Exclude; type T4 = Extract ; console.log(T3, T4);
type Roles = 'admin' | 'user'; type RoleNames = Record; let roles: RoleNames = { admin: 'Alice', user: 'Bob' }; console.log(roles);
interface Person { name: string; age: number; address: string }
type NameAndAge = Pick;
let p: NameAndAge = { name: 'Alice', age: 30 };
console.log(p);
interface Person { name: string; age: number; address: string }
type WithoutAddress = Omit;
let p: WithoutAddress = { name: 'Bob', age: 25 };
console.log(p);
let maybeString: string | null = 'Hello';
console.log(maybeString!.length);
let someValue: any = 'this is a string';
let strLength: number = (someValue as string).length;
console.log(strLength);
interface StringArray { [index: number]: string; }
let myArray: StringArray = ['Alice', 'Bob'];
console.log(myArray[0]);
interface Person { name: string; friend?: { name: string } }
let alice: Person = { name: 'Alice' };
console.log(alice.friend?.name);
let foo = null ?? 'default';
console.log(foo);
function isString(value: any): value is string { return typeof value === 'string'; }
let x: any = 'hello';
if (isString(x)) { console.log(x.length); }
interface Square { kind: 'square'; size: number }
interface Rectangle { kind: 'rectangle'; width: number; height: number }
type Shape = Square | Rectangle;
function area(shape: Shape) {
switch(shape.kind) {
case 'square': return shape.size * shape.size;
case 'rectangle': return shape.width * shape.height;
}
}
console.log(area({ kind: 'square', size: 5 }));
type OptionsFlags= { [Property in keyof Type]: boolean }; interface Features { darkMode: () => void; newUI: () => void } type FeatureOptions = OptionsFlags ; console.log(FeatureOptions);
type Check= T extends string ? 'Yes' : 'No'; type Result = Check ; console.log(Result);
type GetReturnType= T extends (...args: any[]) => infer R ? R : never; function fn() { return 42; } type ReturnTypeOfFn = GetReturnType ; console.log(ReturnTypeOfFn);
type EventName = 'click' | 'hover';
type PrefixedEvent = `on${Capitalize}`;
console.log(PrefixedEvent);
interface Person { name: string; age: number }
type PartialPerson = Partial;
let p: PartialPerson = { name: 'Alice' };
console.log(p);
type RequiredPerson = Required; let rp: RequiredPerson = { name: 'Alice', age: 30 }; console.log(rp);
type ReadonlyPerson = Readonly; let rp: ReadonlyPerson = { name: 'Bob', age: 25 }; // rp.age = 30; // Error console.log(rp);
type PickPerson = Pick; let pp: PickPerson = { name: 'Charlie' }; console.log(pp);
type OmitPerson = Omit; let op: OmitPerson = { name: 'Dana' }; console.log(op);
type Role = 'admin' | 'user'; type RoleMapping = Record; let roles: RoleMapping = { admin: 'Alice', user: 'Bob' }; console.log(roles);
interface A { a: string }
interface B { b: number }
type AB = A & B;
let ab: AB = { a: 'hello', b: 10 };
console.log(ab);
type StringOrNumber = string | number;
let value: StringOrNumber = 'text';
value = 42;
console.log(value);
let num = 10; // inferred as number
let str = 'hello'; // inferred as string
console.log(num, str);
function merge(obj1: T, obj2: U) { return { ...obj1, ...obj2 }; } console.log(merge({ a: 1 }, { b: 2 }));
interface Car { make: string; model: string }
type CarKeys = keyof Car;
let key: CarKeys = 'make';
console.log(key);
let age = 30;
type AgeType = typeof age;
let myAge: AgeType = 40;
console.log(myAge);
type Flatten= T extends any[] ? T[number] : T; type Result = Flatten ; // string console.log(Result);
type NestedArray= T | NestedArray []; let nums: NestedArray = [1, [2, [3]]]; console.log(nums);
type Mutable= { -readonly [P in keyof T]: T[P] }; interface Point { readonly x: number; readonly y: number } type MutablePoint = Mutable ; console.log(MutablePoint);
function getProperty(obj: T, key: K) { return obj[key]; } const car = { make: 'Toyota', model: 'Camry' }; console.log(getProperty(car, 'model'));
type ToArray= T extends any ? T[] : never; type StrOrNumArray = ToArray ; // string[] | number[] console.log(StrOrNumArray);
type Event = 'click' | 'hover';
type Handlers = `${Event}Handler`;
let clickHandler: Handlers = 'clickHandler';
console.log(clickHandler);
type ReturnTypeOf= T extends (...args: any) => infer R ? R : never; function fn() { return 123; } type R = ReturnTypeOf ; console.log(R);
interface Person { name: string; age: number; }
type AgeType = Person['age'];
let myAge: AgeType = 30;
console.log(myAge);
interface StringNumberMap { [key: string]: number }
let map: StringNumberMap = { a: 1, b: 2 };
console.log(map);
type ExtractString= T extends string ? T : never; type Test = ExtractString ; // string console.log(Test);
type DeepReadonly= { readonly [K in keyof T]: T[K] extends object ? DeepReadonly : T[K] }; interface Nested { a: { b: number } } type ReadonlyNested = DeepReadonly ; console.log(ReadonlyNested);
type Optional= { [K in keyof T]?: T[K] }; interface Config { url: string; port: number } type OptionalConfig = Optional ; console.log(OptionalConfig);
type EventName= `on${Capitalize }`; type ClickEvent = EventName<'click'>; // onClick console.log(ClickEvent);
type FunctionKeys= { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; interface Api { get(): void; name: string } type FnKeys = FunctionKeys ; // 'get' console.log(FnKeys);
type Direction = 'Up' | 'Down';
type Event = `${Direction}Event`;
let e: Event = 'UpEvent';
console.log(e);
function isString(value: T): value is T & string { return typeof value === 'string'; } console.log(isString('Hello'));
type NestedArray= T | NestedArray []; let nums: NestedArray = [1, [2, [3, 4]]]; console.log(nums);
type IsString= T extends string ? true : false; type Check = IsString<'Hello'>; // true console.log(Check);
type DeepPartial= { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P] }; interface Config { url: string; options: { timeout: number } } type PartialConfig = DeepPartial ; console.log(PartialConfig);
type First= T extends [infer F, ...any[]] ? F : never; type F = First<[string, number, boolean]>; // string console.log(F);
type T = string | number | boolean; type Ex = Exclude; // number | boolean type Ext = Extract ; // number | string console.log(Ex, Ext);
interface User { name?: string }
let user: User = {};
console.log(user.name!.toUpperCase()); // Using ! to assert non-null
type DeepReadonly= { readonly [K in keyof T]: T[K] extends object ? DeepReadonly : T[K] }; interface Config { api: { url: string } } type ReadonlyConfig = DeepReadonly ; console.log(ReadonlyConfig);
type ToArray= T extends any ? T[] : never; type Test = ToArray ; // string[] | number[] console.log(Test);
type Mutable= { -readonly [P in keyof T]: T[P] }; interface Point { readonly x: number; readonly y: number } type MutablePoint = Mutable ; console.log(MutablePoint);
type Event= T extends 'click' ? 'ClickEvent' : 'OtherEvent'; type E = Event<'click'>; // ClickEvent console.log(E);
type GetReturnType= T extends (...args: any) => infer R ? R : never; function fn() { return { a: 1, b: 2 } } type R = GetReturnType ; console.log(R);
type Append= [...T, V]; type T1 = Append<[1, 2], 3>; // [1, 2, 3] console.log(T1);
type Rename= { [P in keyof T as P extends K ? N : P]: T[P] }; interface User { firstName: string; lastName: string } type NewUser = Rename ; console.log(NewUser);
type ExcludeStrings= T extends string ? never : T; type Result = ExcludeStrings ; // number | boolean console.log(Result);
type DeepPartial= { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P] }; interface Config { api: { url: string; timeout: number } } type PartialConfig = DeepPartial ; console.log(PartialConfig);
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any) { return a + b; }
console.log(combine(1, 2));
console.log(combine('Hello', 'World'));
type ElementType= T extends (infer U)[] ? U : T; type E = ElementType ; // number console.log(E);
type First= T extends [infer F, ...any[]] ? F : never; type F = First<[string, number, boolean]>; // string console.log(F);
function isNumber(value: T): value is T & number { return typeof value === 'number'; } console.log(isNumber(123));
type RenameKeys= { [P in keyof T as P extends K ? N : P]: T[P] }; interface User { firstName: string; lastName: string } type NewUser = RenameKeys ; console.log(NewUser);
type RemoveString= T extends string ? never : T; type Result = RemoveString ; // number | boolean console.log(Result);