Sunday, September 28, 2025

Learn TypeScript from Scratch to Advanced: Complete Tutorial and Interview Questions and answers

 TypeScript has become one of the most in-demand programming languages for web development. It powers frameworks like Angular, works seamlessly with React and Node.js, and is widely adopted by companies for building scalable applications. If you’re preparing for interviews or want to upgrade your JavaScript skills, this TypeScript tutorial with interview questions will take you from beginner to advanced step by step.


πŸ”Ή What is TypeScript?

TypeScript is a superset of JavaScript developed by Microsoft. It adds static typing, interfaces, generics, and object-oriented programming (OOP) concepts on top of JavaScript. The TypeScript compiler (tsc) converts TypeScript code into plain JavaScript, making it compatible with any browser or framework.

Why TypeScript?

  • Early error detection with static typing

  • Enhanced IDE support (IntelliSense, autocompletion)

  • Better maintainability for large projects

  • Supports modern ES6+ features


πŸ”Ή Setting up TypeScript

  1. Install Node.js (download from nodejs.org)

  2. Install TypeScript globally

    npm install -g typescript
  3. Check version

    tsc -v
  4. Compile TypeScript file

    tsc index.ts node index.js

πŸ”Ή TypeScript Basics (Beginner Level)

1. Data Types

let username: string = "Cherry"; let age: number = 12; let isAdmin: boolean = true; let scores: number[] = [10, 20, 30]; let tupleExample: [string, number] = ["Hasitha", 6];

2. Functions

function greet(name: string): string { return `Hello, ${name}`; } console.log(greet("CherryGPT"));

3. Interfaces

interface User { id: number; name: string; } let user: User = { id: 1, name: "Hasitha" };

4. Enums

enum Role { Admin, User, Guest } let myRole: Role = Role.Admin;

πŸ”Ή Intermediate TypeScript

1. Classes & Inheritance

class Animal { constructor(public name: string) {} speak(): void { console.log(`${this.name} makes a sound`); } } class Dog extends Animal { speak(): void { console.log(`${this.name} barks`); } } let dog = new Dog("Tommy"); dog.speak();

2. Generics

function identity<T>(value: T): T { return value; } console.log(identity<string>("Hello")); console.log(identity<number>(123));

3. Type Aliases & Union Types

type ID = number | string; let userId: ID = 101; userId = "abc123";

4. Modules & Namespaces

// mathUtils.ts export function add(a: number, b: number): number { return a + b; } // index.ts import { add } from "./mathUtils"; console.log(add(5, 10));

πŸ”Ή Advanced TypeScript Concepts

1. Advanced Types

type Person = { name: string }; type Employee = Person & { salary: number }; let emp: Employee = { name: "Cherry", salary: 50000 };

2. Decorators (used in Angular)

function Logger(target: any) { console.log("Logging...", target); } @Logger class TestClass {}

3. Type Guards

function printId(id: string | number) { if (typeof id === "string") { console.log("String ID:", id.toUpperCase()); } else { console.log("Number ID:", id); } }

4. Utility Types

interface Todo { title: string; description: string; completed: boolean; } type PartialTodo = Partial<Todo>; type ReadonlyTodo = Readonly<Todo>;

πŸ”Ή TypeScript Best Practices

  • Always define types or interfaces

  • Use strict mode in tsconfig.json

  • Prefer readonly and private where possible

  • Keep functions pure and modular

  • Use Enums/Constants instead of magic numbers


πŸ”Ή TypeScript Interview Questions and Answers

Beginner Level

Q1: What is TypeScript and how is it different from JavaScript?
πŸ‘‰ TypeScript is a superset of JavaScript that adds type safety, interfaces, generics, and OOP features. Unlike JavaScript, TypeScript code needs to be compiled into JS.

Q2: What are the basic data types in TypeScript?
πŸ‘‰ string, number, boolean, null, undefined, tuple, enum, any, void, unknown.

Q3: What is an interface in TypeScript?
πŸ‘‰ An interface defines the structure of an object. It enforces contracts between code.


Intermediate Level

Q4: What are Generics in TypeScript?
πŸ‘‰ Generics allow writing reusable functions and classes that work with multiple types. Example:

function identity<T>(arg: T): T { return arg; }

Q5: Difference between type and interface in TypeScript?
πŸ‘‰ Both define object shapes, but type can represent unions, primitives, and mapped types, whereas interface is best for object contracts and can be extended multiple times.

Q6: What is the difference between unknown and any?
πŸ‘‰ any disables type checking completely. unknown is safer; you must check its type before using it.


Advanced Level

Q7: Explain Decorators in TypeScript.
πŸ‘‰ Decorators are special functions that modify classes, methods, or properties. They are heavily used in Angular for metadata annotations.

Q8: What are Utility Types in TypeScript?
πŸ‘‰ Predefined types like Partial<T>, Pick<T>, Readonly<T>, Record<K,T> that help in transforming object types.

Q9: How does TypeScript improve large-scale application development?
πŸ‘‰ By enforcing type safety, modularization, OOP principles, and preventing runtime errors, making code maintainable and scalable.

✅ Conclusion

TypeScript is not just an extension of JavaScript—it’s a game-changer for modern development. By learning the fundamentals, moving into advanced topics, and preparing with interview questions, you can become a confident TypeScript developer ready for real-world projects and interviews.

Saturday, September 27, 2025

Integrate AI/ML models using services Azure Cognitive Services, OpenAI, or custom models

 This means you can add Artificial Intelligence (AI) and Machine Learning (ML) capabilities to your application in three main ways. Let’s detail each one with examples, use cases, advantages, and considerations.


1. Azure Cognitive Services

Azure Cognitive Services is Microsoft’s suite of ready-made AI APIs that developers can easily plug into their apps without building or training models from scratch.

πŸ”Ή Examples of Services

  • Vision → Image recognition, OCR (text from images), facial recognition, object detection.

  • Speech → Speech-to-text, text-to-speech, speech translation.

  • Language → Sentiment analysis, translation, text analytics, QnA Maker.

  • Decision → Personalizer (recommendation system), anomaly detector.

πŸ”Ή How Integration Works

  • You call REST APIs or use SDKs (C#, Python, Java, etc.).

  • Example: Upload an image → API returns labels like “dog, grass, outdoor”.

var client = new ComputerVisionClient( new ApiKeyServiceClientCredentials("<API_KEY>") ) { Endpoint = "<ENDPOINT>" }; var result = await client.AnalyzeImageAsync(imageUrl, new List<VisualFeatureTypes?> { VisualFeatureTypes.Tags });

✅ Advantages

  • No ML expertise needed.

  • Scalable and secure (hosted on Azure).

  • Pre-trained on massive datasets.

⚠️ Considerations

  • Limited customization.

  • Pay per API call → cost grows with usage.


2. OpenAI (like ChatGPT, GPT models, DALL·E, Whisper)

OpenAI provides powerful foundation AI models that can be integrated for natural language understanding, text generation, image creation, and more.

πŸ”Ή Examples

  • GPT models (ChatGPT, GPT-4, GPT-3.5, GPT-5) → Text generation, Q&A, summarization, code assistance.

  • DALL·E → Image generation from text prompts.

  • Whisper → Speech-to-text transcription.

πŸ”Ή How Integration Works

  • Use Azure OpenAI Service (enterprise version) or OpenAI API directly.

  • Example: Asking GPT to summarize a customer support ticket.

import openai openai.api_key = "YOUR_API_KEY" response = openai.ChatCompletion.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a support assistant."}, {"role": "user", "content": "Summarize the following ticket: ..."} ] ) print(response['choices'][0]['message']['content'])

✅ Advantages

  • State-of-the-art AI (very flexible).

  • Can be fine-tuned for specific domains.

  • Supports multiple modalities (text, image, audio).

⚠️ Considerations

  • Requires careful prompt engineering for best results.

  • Sensitive to input phrasing (outputs may vary).

  • Pricing is token-based (input + output length).


3. Custom Models (Train Your Own ML/AI Models)

This approach means you build your own machine learning models when pre-built services don’t fit your needs.

πŸ”Ή Steps to Build Custom Models

  1. Data Collection → Gather training datasets (structured, images, text, etc.).

  2. Model Training → Use frameworks like TensorFlow, PyTorch, Scikit-learn, or Azure Machine Learning.

  3. Deployment → Package as a REST API (Flask, FastAPI, or Azure ML deployment).

  4. Integration → Application calls your model API just like Cognitive Services.

πŸ”Ή Example

Custom fraud detection in a banking app:

  • Train a classification model with transaction data.

  • Deploy on Azure Machine Learning or Azure Kubernetes Service (AKS).

  • Application sends transaction data → Model predicts fraud probability.

from fastapi import FastAPI import joblib app = FastAPI() model = joblib.load("fraud_model.pkl") @app.post("/predict") def predict(transaction: dict): features = [transaction['amount'], transaction['location'], transaction['device']] prediction = model.predict([features]) return {"fraud": bool(prediction[0])}

✅ Advantages

  • Full customization.

  • Can train on your proprietary data.

  • Better suited for domain-specific use cases (healthcare, finance, retail).

⚠️ Considerations

  • Requires ML expertise (data science + model training).

  • Need infrastructure to train and host models.

  • Higher time and cost investment.


πŸ”‘ Quick Comparison

ApproachBest ForEffort LevelCustomizationExamples
Azure Cognitive ServicesQuick AI integration, standard use casesLowLowOCR, sentiment analysis
OpenAIConversational AI, creative tasksMediumMedium (via fine-tuning, prompts)Chatbots, summarizers
Custom ModelsDomain-specific solutionsHighHighFraud detection, medical AI

πŸ‘‰ So in practice:

  • If you want fast integration → Use Azure Cognitive Services.

  • If you need natural language or generative AI → Use OpenAI.

  • If you need business-specific intelligence → Build Custom Models.

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages