Skip to content

learning-zone/typescript-basics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 

Repository files navigation

Typescript Basics

Click ★ if you like the project. Your contributions are heartily ♡ welcome.


Q. What are the typescript features?

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. Typescript is an extension of ES6.

  • TypeScript includes Interfaces, Classes, Enums, Type Inference, Generics, access modifiers, Function etc. TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference.

  • TypeScript supports new ECMAScript standards and compiles them to (older) ECMAScript targets of your choosing. This means that you can use features of ES2015 and beyond, like modules, lambda functions, classes, the spread operator, destructuring etc.

  • With strict null checks enabled (--strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type.

  • The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. This makes it possible to set breakpoints and inspect variables during runtime directly on TypeScript code.

Q. How to pass optional parameter in typescript?

Optional Parameter Syntax

function functionName(par1: number, par2?: number) {
 
}

Example:

function getSchool(name: string, address?: string, pinCode?: string): string {
    //...
}
 
let school = getSchool("Elementary");
let school2 = getSchool("Little Kid", "UK");  
let school3 = getSchool("Rose Tree School", "US", "99501")

Q. How to declare variable so that it can hold multiple values?

Tuples:

It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions.

Syntax:

let tuple_name = [value1, value2, value3, value n]

Example:

let employee: [number, string] = [10, "Pradeep"]; // Create a tuple 
console.log(employee[0]); // Output: 10
console.log(employee[1]); // Output: Pradeep

Q. Explain generics in TypeScript?

Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type.

Example:

/**
 * Generics
 */
function getArray<T>(items : T[] ) : T[] {
    return new Array<T>().concat(items);
}

let numArr = getArray<number>([10, 20, 30]);
let strArr = getArray<string>(["Hello", "World"]);

numArr.push(40); // OK
strArr.push("Hello TypeScript"); // OK

numArr.push("Hi"); // Compiler Error
strArr.push(50); // Compiler Error

Q. How to implement class constants in TypeScript?

In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with A class member cannot have the 'const' keyword. TypeScript 2.0 has the readonly modifier.

Example:

class MyClass {
    readonly myReadonlyProperty = 1;

    myMethod() {
        console.log(this.myReadonlyProperty);
    }
}

new MyClass().myReadonlyProperty = 5; // error, readonly

Q. What is getters and setters in TypeScript?

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. Getters enable us to bind a property to a function that is called when the property is accessed, whereas setters bind a property to a function that is called on attempts to set the property.

Example:

/**
 * Getters and Setters
 */
class Employee {
  private _name: string;

  get Name() {
    return this._name;
  }
  set Name(val) {
    this._name = val;
  }
}

let employee = new Employee();
employee.Name = "Pradeep";

console.log("Name" + employee.Name); // Pradeep

Try this example on CodeSandbox

Q. Is that TypeScript code valid?

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

Yes, the code is valid. A class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, we can use them in the same places we would be able to use interfaces.

Q. Explain decorators in TS?

Decorators can be used to modify the behavior of a class or become even more powerful when integrated into a framework. For instance, if your framework has methods with restricted access requirements (just for admin), it would be easy to write an @admin method decorator to deny access to non-administrative users, or an @owner decorator to only allow the owner of an object the ability to modify it.

Example:

/**
 * Decorators
 */
class Employee {
    get() { }
    post() { }

    @admin
    delete() { }

    @owner
    put() { }
}

Q. What is the difference between interface and type statements?

Interface Type
An interface declaration always introduces a named object type. A type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
An interface can be named in an extends or implements clause. Type alias for an object type literal cannot be named in an
Interfaces create a new name that is used everywhere. Type aliases don't create a new name.
An interface can have multiple merged declarations. Type alias for an object type literal cannot have multiple merged declarations.

Example:

/**
 * Interface vs Type
 */
interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};

Q. What is Rest parameters?

The rest parameter is used to pass zero or more values to a function. It is declared by prefixing the three dot characters ('...') before the parameter. It allows the functions to have a variable number of arguments without using the arguments object.

Rules:

  • Only one rest parameter is allowed in a function.
  • It must be an array type.
  • It must be a last parameter in the parameter list.

Example:

/**
 * Rest parameters
 */
function sum(a: number, ...b: number[]): number {    
    let result = a;    
    for (let i = 0; i < b.length; i++) {    
        result += b[i];    
    }    
    console.log(result);    
}    
let result1 = sum(3, 5);    
let result2 = sum(3, 5, 7, 9);   

Q. Explain enum datatype in TypeScript?

Enums or enumerations are a TypeScript data type that allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. It is a collection of related values that can be numeric or string values.

Example:

/**
 * Enum Datatype
 */
enum Gender {  
  Male,  
  Female  
  Other  
}  
console.log(Gender.Female); // Output: 1  
//We can also access an enum value by it's number value.  
console.log(Gender[1]); // Output: Female  

Q. What is the difference between an Interface and a Class in TypeScript?

Interface Class
Only exists at compile time; erased from the emitted JS. Exists at both compile time and runtime.
Cannot contain implementation — only signatures. Can contain full method implementations and constructors.
Cannot be instantiated with new. Can be instantiated with new.
Supports declaration merging. Does not support declaration merging.

Example:

interface Animal {
    name: string;
    speak(): void;
}

class Dog implements Animal {
    constructor(public name: string) {}
    speak() {
        console.log(`${this.name} says: Woof!`);
    }
}

const dog = new Dog("Rex");
dog.speak(); // Rex says: Woof!

Q. What are Discriminated Union types in TypeScript?

A discriminated union (also called a tagged union) combines union types with a common literal property — the discriminant — that TypeScript uses to narrow the type in control flow.

Example:

interface Circle {
    kind: "circle";
    radius: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

type Shape = Circle | Rectangle;

function getArea(shape: Shape): number {
    switch (shape.kind) {
        case "circle":
            return Math.PI * shape.radius ** 2;
        case "rectangle":
            return shape.width * shape.height;
    }
}

console.log(getArea({ kind: "circle", radius: 5 }));       // 78.53...
console.log(getArea({ kind: "rectangle", width: 4, height: 6 })); // 24

Q. Why do you need type definitions (.d.ts files)?

Type definition files describe the shape of JavaScript libraries so TypeScript can type-check code that uses them without requiring the library itself to be written in TypeScript.

  • They enable IntelliSense, autocompletion, and compile-time error checking for JS libraries.
  • Published as @types/<package> on npm (e.g. @types/node, @types/react).
  • You can also write your own .d.ts file for an untyped library using declare module.

Example:

// custom.d.ts
declare module "my-untyped-lib" {
    export function greet(name: string): string;
}

Q. How do you define a custom type in TypeScript?

Use the type keyword to create a type alias for any type expression.

Example:

// Primitive alias
type ID = string | number;

// Object shape
type User = {
    id: ID;
    name: string;
    email: string;
};

// Function type
type Formatter = (value: string) => string;

const toUpper: Formatter = (v) => v.toUpperCase();

const user: User = { id: 1, name: "Alice", email: "alice@example.com" };
console.log(toUpper(user.name)); // ALICE

Q. How do you define an Object of Objects type in TypeScript?

Use an index signature or a mapped type to describe a dictionary whose values are themselves objects.

Example:

type Address = {
    city: string;
    country: string;
};

// Index signature — keys are strings, values are Address objects
type AddressBook = {
    [userId: string]: Address;
};

const book: AddressBook = {
    user1: { city: "New York", country: "US" },
    user2: { city: "London",   country: "UK" },
};

console.log(book["user1"].city); // New York

Q. What is the unknown type and how does it differ from any?

any unknown
Disables all type checking — you can perform any operation on it. Type-safe counterpart — you must narrow the type before using it.
Assignable to and from any type. Assignable from any type, but only assignable to unknown or any.

Example:

let a: any = "hello";
a.toFixed();  // No error, but crashes at runtime

let b: unknown = "hello";
// b.toFixed();  // Compiler error — must narrow first

if (typeof b === "string") {
    console.log(b.toUpperCase()); // HELLO — safe
}

Q. What are utility types in TypeScript?

TypeScript ships built-in utility types that transform existing types into new ones.

Utility Type Description
Partial<T> Makes all properties of T optional.
Required<T> Makes all properties of T required.
Readonly<T> Makes all properties of T read-only.
Pick<T, K> Picks a subset of properties K from T.
Omit<T, K> Removes properties K from T.
Record<K, T> Creates an object type with keys K and values T.
ReturnType<T> Extracts the return type of a function type T.

Example:

interface User {
    id: number;
    name: string;
    email: string;
}

type PartialUser = Partial<User>;          // all fields optional
type PublicUser  = Omit<User, "email">;    // id + name only
type UserMap     = Record<string, User>;   // string-keyed dictionary

Q. What is type narrowing in TypeScript?

Type narrowing is the process by which TypeScript refines a broad type to a more specific one inside a conditional block, using type guards.

Common type guards:

  • typeof — for primitives
  • instanceof — for class instances
  • in — for object property checks
  • Custom type predicates (value is Type)

Example:

function printLength(value: string | number) {
    if (typeof value === "string") {
        console.log(value.length);    // string branch
    } else {
        console.log(value.toFixed(2)); // number branch
    }
}

// Custom type predicate
interface Cat { meow(): void; }
interface Dog { bark(): void; }

function isCat(pet: Cat | Dog): pet is Cat {
    return (pet as Cat).meow !== undefined;
}

About

Typescript Basics ( v6.x )

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors