Created by Sergey Gorin
I will tell you why Typescript is needed, what its
advantages are and much more.
Stay tuned.
Why is that?!
let a = "Hello, World!"
let b = 42.69
let c = true || false
// Type annotation for a variable
let age: number;
let name: string;
let isStudent: boolean;
age = 25; // Valid
name = "John"; // Valid
isStudent = true; // Valid
age = "25"; // Error: Type "25" is not type 'number'
// Function with type annotations
function addN(n1: number, n2: number): number {
return n1 + n2;
}
const result = addN(5, 10); // result will be 15 (number)
addN("5", 10); // Error: "5" is not type 'number'.
// Array with type annotation
let n: number[] = [1, 2, 3, 4];
let f: string[] = ["apple", "banana", "orange"];
n.push(5); // Valid
n.push("6"); // Error:'string' is not type 'number'.
f.push("grape"); // Valid
f.push(123); // Error: 'number' is not type 'string'.
For what?!
// Interface for an object
interface Person {
name: string;
age: number;
isStudent: boolean;
}
// Object with specified type
const person: Person = {
name: "John",
age: 25,
isStudent: true,
};
interface Person {
name: string;
age: number;
isStudent: boolean;
}
const person: Person = {
name: "Jane",
age: 30,
};
// Error: Property 'isStudent' is missing in type
// '{ name: string; age: number; }'
// but required in type 'Person'.
// Base interface
interface Shape {
color: string;
}
// Extended interface
interface Circle extends Shape {
radius: number;
}
// Object that conforms to the Circle interface
const circle: Circle = { color: "red", radius: 5 };
And use them for object-oriented programming
class Animal {
// Properties
name: string;
age: number;
// Constructor
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method
makeSound() {
console.log("Animal makes a sound.");
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, age: number, breed: string) {
super(name, age);
this.breed = breed;
}
// Overriding the makeSound method
makeSound() {
console.log("Woof! Woof!");
}
}
const germanShepherd = new Dog("Max", 5, "German Shepherd");
germanShepherd.makeSound(); // Output: "Woof! Woof!"
console.log(germanShepherd.name); // Output: "Max"
console.log(germanShepherd.breed); // Output: "German Shepherd"
class AnyClass {
public property: string;
private secret: number;
protected info: string;
}
// Interface for a Flyable object
interface Flyable {
fly(): void;
}
// Bird class implementing the Flyable interface
class Bird extends Animal implements Flyable {
constructor(name: string) {
super(name);
}
makeSound() {
console.log("Bird chirps.");
}
fly() {
console.log("Bird flies in the sky.");
}
}
So complicated...
// Generic function that accepts an array and
// returns its first element
function getFirstElement < T>(arr: T[]): T {
return arr[0];
}
// Usage
const n = [1, 2, 3];
const f = ["apple", "banana", "orange"];
const firstN = getFirstElement(n); // Type of firstN is number
const firstF = getFirstElement(f); // Type of firstF is string
// Generic class that holds a value of type T
class Box< T> {
private value: T;
constructor(initialValue: T) {
this.value = initialValue;
}
getValue(): T {
return this.value;
}
}
// Usage
const numberBox = new Box< number>(10);
// Create a Box with a number value
const stringBox = new Box< string>("Hello");
// Create a Box with a string value
const numberValue = numberBox.getValue();
// Type of numberValue is number
const stringValue = stringBox.getValue();
// Type of stringValue is string
// Generic function with a constraint that
// the type must have a 'length' property
function getArrayLength< T extends { length: number }>
(arr: T): number {
return arr.length;
}
const numbers = [1, 2, 3];
const fruits = ["apple", "banana", "orange"];
const numbersLength = getArrayLength(numbers); // Valid
const fruitsLength = getArrayLength(fruits); // Valid
const str = "Hello";
const strLength = getArrayLength(str);
// Error: Type 'string' does not have a 'length' property
Wow, amazing!
// Example of built-in decorators
class Example {
@deprecated
someMethod() {
console.log("This method is deprecated.");
}
@readonly
readonlyProperty = "This property is read-only.";
@experimental
experimentalMethod() {
console.log("This method is experimental.");
}
@sealed
sealedProperty = "This property is sealed.";
}
// Custom decorator example
function logMethod(target: any, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling method ${key} with arguments ${args}`);
const result = originalMethod.apply(this, args);
console.log(`Method ${key} returned ${result}`);
return result;
};
return descriptor;
}
class MathOperations {
@logMethod
add(a: number, b: number) {
return a + b;
}
}
const math = new MathOperations();
console.log(math.add(2, 3)); // Output: "Calling method add with arguments 2,3", "Method add returned 5", 5
TypeScript offers numerous advantages and has become a crucial tool in modern software development