TypeScript: A Superset of JavaScript for Large-Scale Application Development

This guide introduces TypeScript, a powerful superset of JavaScript that adds static typing and other features beneficial for large-scale projects. Learn about its key advantages over JavaScript, explore its features, and understand why TypeScript is a popular choice for building robust and maintainable applications.



TypeScript Interview Questions and Answers

What is TypeScript?

Question 1: What is TypeScript?

TypeScript is a free and open-source programming language developed and maintained by Microsoft. It's a superset of JavaScript, adding optional static typing and other features that make it suitable for large-scale application development. TypeScript code is compiled into JavaScript, which runs in web browsers.

TypeScript vs. JavaScript

Question 2: TypeScript vs. JavaScript

Key differences:

Feature TypeScript JavaScript
Typing Statically-typed (optional); supports type annotations. Dynamically-typed; no type annotations required.
Error Checking Compile-time error checking. Runtime error checking.
Object-Oriented Programming (OOP) Supports classes, interfaces, inheritance. Supports prototypes and classes (ECMAScript 2015 and later).
Modules Supports modules. Supports modules (ES6 and later).
Generics Supports generics. Does not support generics (until newer versions of JavaScript).
Optional Parameters Supports optional parameters. Supports optional parameters (newer versions of Javascript).

Learn More About TypeScript vs. JavaScript

Why Use TypeScript?

Question 3: Why Use TypeScript?

Reasons to use TypeScript:

  • Improved Code Maintainability: Type annotations make code easier to understand and maintain.
  • Early Error Detection: Compile-time error checking catches issues before runtime.
  • Enhanced Productivity: Features like autocompletion and type checking speed up development.
  • Support for Modern JavaScript Features: TypeScript supports the latest JavaScript features.
  • Code Reusability: Supports object-oriented programming concepts like classes, inheritance, and interfaces.

TypeScript Features

Question 4: Features of TypeScript

(This would list key TypeScript features, such as interfaces, types, classes, generics, namespaces (modules), and support for optional parameters and more.)

Learn More About TypeScript Features

Benefits of TypeScript

Question 5: Benefits of Using TypeScript

Benefits of using TypeScript:

  • Optional static typing.
  • Compile-time error checking.
  • Improved code organization.
  • Support for modern JavaScript features.
  • Better tooling support.

Disadvantages of TypeScript

Question 6: Disadvantages of TypeScript

Potential downsides of TypeScript:

  • Slower compilation times.
  • Requires a compilation step.
  • Learning curve for developers unfamiliar with static typing.
  • Type definition files (`.d.ts`) are needed for third-party libraries.

TypeScript Components

Question 7: Components of TypeScript

TypeScript consists of:

  • Language: The TypeScript language itself.
  • Compiler (tsc): Transpiles TypeScript to JavaScript.
  • Language Service: Provides support for IDE features (like IntelliSense).

TypeScript Development Team and Versions

Question 8: TypeScript Development Team and Versions

TypeScript was created by Anders Hejlsberg (also known for his work on C#). The current stable version should be stated here and updated as needed.

Installing TypeScript

Question 9: Installing TypeScript

TypeScript is installed using npm (Node Package Manager):

Command

npm install -g typescript

This installs the TypeScript compiler (`tsc`) globally.

Learn More About TypeScript Installation

Built-in Types in TypeScript

Question 10: Built-in Types in TypeScript

TypeScript's built-in types:

  • number (all numbers are floating-point).
  • string (Unicode UTF-16).
  • boolean (true/false).
  • null (represents an undefined value).
  • undefined (represents an uninitialized variable).
  • void (return type for functions that don't return a value).
Example: Type Annotations

let age: number = 30;
let name: string = "Alice";
let isAdult: boolean = true;

TypeScript vs. JavaScript (Continued)

Question 2: TypeScript vs. JavaScript (Continued)

TypeScript extends JavaScript by adding optional static typing. This improves code quality and maintainability, especially in larger projects.

Why Use TypeScript? (Continued)

Question 3: Why Use TypeScript? (Continued)

TypeScript offers many benefits:

  • Improved Code Readability: Type annotations make code easier to understand.
  • Early Error Detection: The compiler catches type errors before runtime.
  • Enhanced Developer Productivity: Features like autocompletion and refactoring tools speed up development.
  • Support for Modern JavaScript: TypeScript supports the latest ECMAScript features.
  • Code Reusability: OOP features (classes, inheritance) promote reusability.

TypeScript Components

Question 7: Components of TypeScript

TypeScript has three core components:

  • Language: The TypeScript language itself (syntax, types, keywords).
  • Compiler (tsc): Transpiles TypeScript code into JavaScript.
  • Language Service: Supports IDE features (like IntelliSense, autocompletion).

TypeScript Development and Versions

Question 8: TypeScript Development Team and Versions

TypeScript was developed by Anders Hejlsberg at Microsoft. (State the current latest stable version of TypeScript here. This will need to be updated periodically.)

Installing TypeScript

Question 9: Installing TypeScript

Steps:

  1. Install Node.js.
  2. Install TypeScript globally using npm (Node Package Manager): npm install -g typescript
  3. Verify installation: tsc --version

Learn More About TypeScript Installation

Built-in Types in TypeScript

Question 10: Built-in Types in TypeScript

Built-in types:

  • number (floating-point).
  • string (UTF-16).
  • boolean (true/false).
  • null.
  • undefined.
  • void (return type for functions with no return value).
  • symbol (unique and immutable values).
  • bigint (arbitrary-precision integers).
Example: Type Annotations

let age: number = 30;
let name: string = "Alice";
let isAdult: boolean = true;
let bigNum: bigint = 1234567890123456789n;
let unique: symbol = Symbol("unique");

Variables in TypeScript

Question 11: Variables in TypeScript

Variables store data. They must be declared before use. In TypeScript, variables can be declared using `var`, `let`, or `const`. Type annotations are optional but recommended.

Declaration methods:

  • var identifier: type = value;
  • var identifier: type;
  • var identifier = value;
  • var identifier;

Learn More About TypeScript Variables

Compiling TypeScript

Question 12: Compiling TypeScript Files

Use the TypeScript compiler (`tsc`) to compile TypeScript (`.ts`) files into JavaScript (`.js`) files. The basic syntax is: tsc filename.ts.

Compiling a Single File

tsc helloworld.ts
Compiling Multiple Files into One

tsc --outFile combined.js file1.ts file2.ts

Watch Mode Compilation

Question 14: Compiling with Watch Mode

Use the `--watch` flag to automatically recompile TypeScript files whenever changes are saved. The command prompt needs to remain open.

Command

tsc --watch myFile.ts

Interfaces in TypeScript

Question 15: Interfaces

Interfaces define contracts specifying the shape of an object. Classes that implement an interface must provide implementations for all of its members. They are not directly executable; their purpose is for type checking during compilation.

Example: Interface

interface Person {
    name: string;
    age: number;
    greet(): void;
}

Classes in TypeScript

Question 16: Classes in TypeScript

Classes are blueprints for creating objects. They encapsulate data (properties) and behavior (methods). Classes are a fundamental aspect of object-oriented programming and support inheritance, encapsulation, and polymorphism.

Example: Class

class Student {
    studCode: number;
    studName: string;
    constructor(code: number, name: string) {
        this.studName = name;
        this.studCode = code;
    }
    getGrade(): string {
        return "A+"; 
    }
}
let student1 = new Student(101, "Alice");
console.log(student1.getGrade()); // Output: A+

JavaScript Module Support

Question 17: Native JavaScript Module Support

Native JavaScript did not originally support modules; this required external tools, such as CommonJS or AMD.

Object-Oriented Terms in TypeScript

Question 18: Object-Oriented Terms Supported by TypeScript

TypeScript supports classes, interfaces, inheritance, modules, and data types, enabling object-oriented programming techniques.

Calling Base Class Constructor

Question 19: Calling Base Class Constructor

Use the super() keyword to call the superclass constructor from within a subclass constructor in TypeScript.

Inheritance in TypeScript

Question 20: Inheritance in TypeScript

Inheritance is achieved using the `extends` keyword. A subclass inherits properties and methods from its superclass.

Example: Inheritance

class Shape {
    area: number;
    constructor(area: number) { this.area = area; }
}
class Circle extends Shape {
    display(): void {
        console.log("Area of the circle: " + this.area); //Output: Area of the circle: 320
    }
}
let obj = new Circle(320);
obj.display();

Modules in TypeScript

Question 21: Modules in TypeScript

Modules in TypeScript group related code into separate files, helping to organize larger projects and manage dependencies. The `export` keyword makes members accessible from other modules; `import` brings them in.

Example: Module

// moduleA.ts
export function add(x: number, y: number): number {
    return x + y;
}

// moduleB.ts
import { add } from "./moduleA";
console.log(add(5, 3)); // Output: 8

Internal vs. External Modules

Question 22: Internal vs. External Modules

Differences:

Module Type Description
Internal Module (Namespace) Used for organizing code within a single file.
External Module A separate file; requires an explicit import statement.

Namespaces in TypeScript

Question 23: Namespaces

Namespaces in TypeScript provide a way to logically group related declarations (like classes and interfaces). They help to prevent naming conflicts and improve code organization, similar to modules but primarily for organizing within a file. Namespaces are largely superseded by modules in modern TypeScript.

Extending Native Libraries

Question 23: Extending Native Libraries

You can extend CodeIgniter's built-in libraries by creating a new class that inherits from the original library class. This is generally better than replacing the entire library because it allows you to add functionality without affecting the original library's behavior.

Key considerations:

  • The new class must extend the parent library class.
  • The filename and class name should be prefixed with `MY_`.

Learn More About Extending Libraries

Extending Classes

Question 24: Extending Classes

You can extend classes in CodeIgniter by creating a file named `MY_<ClassName>.php` in the `application/core` directory and defining a class that extends the original class (e.g., `CI_Input`). This approach allows you to override methods or add new ones.

Routing in CodeIgniter

Question 25: Routing in CodeIgniter

CodeIgniter routing maps URLs to controllers and methods. Wildcards and regular expressions are used to define flexible routing rules.

Example using Wildcard

$route['products/:num'] = 'products/view/$1'; // :num matches a number
Example using Regular Expression

$route['blog/([a-z0-9]+)'] = 'blog/view/$1'; // Matches alphanumeric characters

Reasons for Configuring Routes

Question 26: Why Configure URL Routes?

Route configuration in CodeIgniter is done to:

  • Create user-friendly URLs.
  • Improve SEO (search engine optimization).
  • Hide underlying code structure from the URLs.

Hooks in CodeIgniter

Question 27: Hooks in CodeIgniter

Hooks provide a way to extend or modify CodeIgniter's core functionality without modifying its core files. You define functions to be executed at specified points during the framework's execution. Hooks are defined in `application/config/hooks.php`.

Enabling Hooks

Question 28: Enabling Hooks

To enable hooks, set $config['enable_hooks'] = TRUE; in your CodeIgniter's `application/config/config.php` file.

Types of TypeScript Decorators

Question 24: TypeScript Decorators

Decorators in TypeScript provide a way to add annotations and metadata to classes, methods, properties, and parameters. They use the `@` symbol followed by an expression that evaluates to a function. This function is executed at runtime, and it can modify the behavior of the decorated element.

Example: Simple Decorator

function myDecorator(target: any, propertyKey: string) {
    console.log("Decorator called!");
}

class MyClass {
    @myDecorator
    myMethod() {
        console.log("Method called"); // Output: Decorator called!, Method called
    }
}

let myInstance = new MyClass();
myInstance.myMethod();

To enable decorator support, add `"experimentalDecorators": true` to your `tsconfig.json` file.

Mixins

Question 25: Mixins

Mixins in JavaScript (and TypeScript) are a technique for reusing code by incorporating functionality from one class into another. A mixin is essentially a function that takes a class and returns a new class with additional methods. It's a way to achieve multiple inheritance-like behavior in JavaScript, which doesn't support traditional multiple inheritance.

Default Visibility in TypeScript Classes

Question 26: Default Visibility

The default visibility for properties and methods in TypeScript classes is `public`.

Optional Parameters

Question 27: Optional Parameters in TypeScript

Unlike JavaScript, TypeScript requires you to specify parameter types. To make parameters optional in TypeScript, add a question mark `?` after the type. Optional parameters must come after required parameters.

TypeScript Function with Optional Parameter

function greet(name: string, greeting?: string): string {
    return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
}
console.log(greet("Alice")); //Output: Hello, Alice!
console.log(greet("Bob", "Good morning")); // Output: Good morning, Bob!

Function Overloading

Question 28: Function Overloading in TypeScript

TypeScript supports function overloading, meaning you can define multiple functions with the same name but different parameter types or numbers of parameters. However, only one function implementation is needed. The compiler determines the function to call based on the provided arguments.

TypeScript Code

function add(a: string, b: string): string;
function add(a: number, b: number): number;
function add(a: any, b: any): any {
    return a + b;
}
console.log(add("Hello", "World")); // Output: HelloWorld
console.log(add(5, 3)); // Output: 8

Debugging TypeScript

Question 29: Debugging TypeScript

Debugging TypeScript requires source maps, which link the compiled JavaScript code back to the original TypeScript code. Compile your TypeScript code with the `--sourcemap` flag (tsc --sourcemap myfile.ts) to generate source map files.

TypeScript Definition Manager (TSD)

Question 30: TypeScript Definition Manager (TSD)

TSD (TypeScript Definition Manager) is a tool for installing and managing TypeScript definition files (`.d.ts`). These files provide type information for JavaScript libraries, allowing you to use them in your TypeScript code without type errors. It's largely superseded by modern package managers.

Including a Definition File

/// <reference path="typings/jquery/jquery.d.ts" />

`declare` Keyword

Question 31: `declare` Keyword

The `declare` keyword in TypeScript is used to declare variables or types that exist outside the current project (e.g., variables from a JavaScript library). It tells the compiler not to issue errors for these undeclared identifiers.

Example using declare

declare var myLib;
myLib.someMethod(); //No Compile Error

Generating Definition Files

Question 32: Generating Definition Files

Use the TypeScript compiler with the `--declaration` flag (e.g., `tsc --declaration myfile.ts`) to generate a declaration file (`.d.ts`) containing type information for your TypeScript code.

`tsconfig.json`

Question 33: tsconfig.json File

The `tsconfig.json` file configures the TypeScript compiler. It specifies options like target ECMAScript version, module system, and other compiler settings.

Example tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
    // ... other options ...
  }
}

Generics in TypeScript

Question 34: Generics in TypeScript

Generics enable you to write reusable code components that can work with various types without losing type safety. You define type parameters (e.g., <T>) which act as placeholders for actual types.

Example: Generic Function

function identity<T>(arg: T): T {
    return arg;
}
let myString: string = identity<string>("hello");
let myNumber: number = identity<number>(10);
console.log(myString); // Output: hello
console.log(myNumber); // Output: 10

Object-Oriented Principles in TypeScript

Question 35: Object-Oriented Principles in TypeScript

TypeScript supports encapsulation, inheritance, polymorphism, and abstraction—the four main principles of object-oriented programming.

Checking for `null` and `undefined`

Question 36: Checking for `null` and `undefined`

In TypeScript, you can check for `null` and `undefined` values using loose equality (`==`) or strict equality (`===`). Loose equality checks for value equality, while strict equality checks for both value and type equality. The `typeof` operator can also be used to check if a variable is `undefined`.

TypeScript Code

var a: number;
var b: number = null;

function check(x: any, name: string) {
    if (x == null) {
        console.log(name + " == null");
    }
    if (x === null) {
        console.log(name + " === null");
    }
    if (typeof x === 'undefined') {
        console.log(name + " is undefined");
    }
}

check(a, "a"); // Output: a == null, a is undefined
check(b, "b"); // Output: b == null, b === null

Using TypeScript on the Backend

Question 37: Using TypeScript on the Backend

Yes, TypeScript can be used on the backend with Node.js. This allows you to leverage TypeScript's features (like type checking) while still generating JavaScript code that can run on a Node.js server.

Steps:

  1. Install the TypeScript compiler: npm i -g typescript
  2. Configure the compiler using `tsconfig.json`.
  3. Compile your TypeScript files using the `tsc` command.
  4. Run the compiled JavaScript code using Node.js.
tsconfig.json Example

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./dist"
  }
}

Interfaces vs. Types

Question 38: Interface vs. Type

Both interfaces and types define the shape of an object, but they differ in some key ways:

Feature Interface Type Alias
Declaration interface MyInterface { ... } type MyType = { ... };
Extends/Implements Can be extended or implemented Cannot be extended or implemented (for object types)
Merging Multiple declarations with the same name are merged Multiple declarations are not permitted (for object types)
Type Creates a new named type Creates an alias for an existing type

Ambient Declarations

Question 39: Ambient Declarations

Ambient declarations in TypeScript tell the compiler about the existence of code that is defined elsewhere (e.g., in a JavaScript library). They're used to integrate external JavaScript code into TypeScript projects without type errors. Ambient declarations do *not* load external code. They merely provide type information to the TypeScript compiler.

TypeScript Map Files

Question 40: TypeScript Map Files

TypeScript map files (`.map` files) allow debuggers to map the compiled JavaScript code back to the original TypeScript source code. This makes debugging TypeScript code significantly easier.

Type Assertions

Question 41: Type Assertions

Type assertions in TypeScript provide a way to tell the compiler to treat an expression as a different type without performing any runtime checks. They are useful when you have a variable of type `any` and you know its actual type.

Example: Type Assertion

let empCode: any = 111;
let employeeCode = empCode as number;
console.log(typeof employeeCode); // Output: number

`as` Syntax for Type Assertions

Question 42: `as` Syntax for Type Assertions

The `as` syntax is an alternative way to perform type assertions in TypeScript. It is often preferred when using JSX.

Example: `as` Syntax

let empCode: any = 111;
let employeeCode = empCode as number;
console.log(typeof employeeCode); // Output: number

JSX in TypeScript

Question 43: JSX in TypeScript

JSX (JavaScript XML) is an XML-like syntax extension to JavaScript. TypeScript supports JSX and allows for type checking and compiling of JSX code. To use JSX, you must use `.tsx` file extensions and enable the `jsx` option in `tsconfig.json`.

Rest Parameters

Question 44: Rest Parameters

Rest parameters in TypeScript allow a function to accept a variable number of arguments. The rest parameter is declared using three dots (`...`) before the parameter name. The parameter must be an array.

TypeScript Code

function sum(a: number, ...b: number[]): number {
    let result = a;
    for (let i = 0; i < b.length; i++) {
        result += b[i];
    }
    return result;
}
console.log(sum(3, 5)); // Output: 8
console.log(sum(3, 5, 7, 9)); // Output: 24

Enums in TypeScript

Question 45: Enums in TypeScript

Enums define a set of named constants. They improve code readability and maintainability. Enum values can be numeric or string literals.

TypeScript Code

enum Gender {
    Male,
    Female,
    Other
}
console.log(Gender.Female); // Output: 1
console.log(Gender[1]); // Output: Female

Relative vs. Non-Relative Imports

Question 46: Relative vs. Non-Relative Imports

In TypeScript:

  • Relative imports: Specify the path relative to the current file (e.g., `./myModule`, `../myModule`).
  • Non-relative imports: Specify a module using its name (e.g., `jquery`, `@angular/core`).

Anonymous Functions

Question 47: Anonymous Functions

Anonymous functions are functions declared without a name. They're often used for short, simple operations. They're frequently used as callbacks.

TypeScript Code

let myAdd = function(x: number, y: number): number {
    return x + y;
};
console.log(myAdd(5,3)); // Output: 8

Declaration Merging

Question 48: Declaration Merging

Declaration merging allows combining multiple declarations with the same name into a single declaration. This is particularly useful for interfaces, where you can extend an interface across multiple files.

TypeScript Code

interface Cloner {
    clone(animal: Animal): Animal;
}
interface Cloner {
    clone(animal: Sheep): Sheep;
}
// ... more interface declarations ...

// The compiler merges these into a single Cloner interface

Method Overriding

Question 49: Method Overriding

Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method must have the same name and parameters in both classes.

TypeScript Code

class Printer {
    doPrint(): any {
        console.log("Called Parent class."); 
    }
}
class NewPrinter extends Printer {
    doPrint(): any {
        super.doPrint(); 
        console.log("Called Child class."); 
    }
    doInkJetPrint(): any {
        console.log("Called doInkJetPrint()."); 
    }
}

let printer = new NewPrinter();
printer.doPrint(); // Output: Called Parent class., Called Child class.
printer.doInkJetPrint(); // Output: Called doInkJetPrint().

Lambda (Arrow) Functions

Question 50: Lambda (Arrow) Functions

Arrow functions in TypeScript provide a concise syntax for writing anonymous functions (functions without a name). They're particularly useful for short, simple functions.

Example: Arrow Function

let sum = (a: number, b: number): number => {
    return a + b;
};
console.log(sum(20, 30)); // Output: 50

Key features of arrow functions:

  • Concise syntax (omitting the `function` keyword).
  • Implicit return (for single-expression functions).
  • Lexical `this` binding.

Learn More About Arrow Functions