FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

36 Advanced TypeScript Interview Questions (ANSWERED) For JavaScript Developers

TypeScript starts from the same syntax and semantics that millions of JavaScript developers know today. Don't miss that advanced list of 36 TypeScript interview questions and answers and nail your next web developer tech interview in style.

Q1: 
Explain generics in TypeScript

Answer

Generics are able to create a component or function to work over a variety of types rather than a single one.

/** A class definition with a generic parameter */
class Queue<T> {
  private data = [];
  push = (item: T) => this.data.push(item);
  pop = (): T => this.data.shift();
}

const queue = new Queue<number>();
queue.push(0);
queue.push("1"); // ERROR : cannot push a string. Only numbers allowed

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q2: 
How to call base class constructor from child class in TypeScript?

Answer

We can call base class constructor using super().


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q3: 
What is TypeScript and why would I use it in place of JavaScript?

Answer

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

In details:

  • 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, today.
  • JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript.
  • TypeScript adds type support to JavaScript. The type system of TypeScript is relatively rich and includes: interfaces, enums, hybrid types, generics, union and intersection types, access modifiers and much more. TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference.
  • The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information.
  • 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.
  • To use TypeScript you need a build process to compile to JavaScript code. The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code.
  • TypeScript is open source (Apache 2 licensed, see github) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project.

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q4: 
Could we use TypeScript on backend and how?

Answer

Typescript doesn’t only work for browser or frontend code, you can also choose to write your backend applications. For example you could choose Node.js and have some additional type safety and the other abstraction that the language brings.

  1. Install the default Typescript compiler
npm i -g typescript
  1. The TypeScript compiler takes options in the shape of a tsconfig.json file that determines where to put built files and in general is pretty similar to a babel or webpack config.
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "build"
  }
}
  1. Compile ts files
tsc
  1. Run
node build/index.js

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q5: 
Describe what are conditional types in TypeScript?

Answer
  • Condtitional types added the ability to express non-uniform type mappings,
  • A conditional type selects one of two possible types based on a condition expressed as a type relationship test

For example:

T extends U ? X : Y

The type above means when T is assignable to U the type is X, otherwise the type is Y.

Evaluation of a conditional type is deferred when evaluation of the condition depends on type variables in T or U, but is resolved to either X or Y when the condition depends on no type variables.

An example:

type TypeName<T> =
    T extends string ? "string" :
    T extends number ? "number" :
    T extends boolean ? "boolean" :
    T extends undefined ? "undefined" :
    T extends Function ? "function" :
    "object";

type T0 = TypeName<string>;  // "string"
type T1 = TypeName<"a">;  // "string"
type T2 = TypeName<true>;  // "boolean"
type T3 = TypeName<() => void>;  // "function"
type T4 = TypeName<string[]>;  // "object"

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
Source: github.com

Q6: 
Does TypeScript support all object oriented principles?

Answer

The answer is YES. There are 4 main principles to Object Oriented Programming:

  • Encapsulation,
  • Inheritance,
  • Abstraction, and
  • Polymorphism.

TypeScript can implement all four of them with its smaller and cleaner syntax.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q7: 
How could you check null and undefined in TypeScript?

Answer

Just use:

if (value) {
}

It will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ''
  • 0
  • false

TypesScript includes JavaScript rules.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q8: 
How do we create an enum with string values?

Answer

String-based enums (TypeScript 2.4) allow us to assign string values to an enum member.

Consider:

enum E {
    hello = "hello",
    world = "world"
};

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
How to implement class constants in TypeScript?

Answer

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:

class MyClass {
    readonly myReadonlyProperty = 1;

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

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

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q10: 
What is Optional Chaining in TypeScript?

Answer

An optional chain is an optional expression followed by one or more subsequent regualr property access, element access, or call argument lists:

a?.b.c; // property access chain
a?.b[x]; // element access chain
a?.b(); // call chain

Which means:

  • When a is either null or undefined, the rest of the chain is also not evaluated.
  • However, if a is any other value, the expression is evaluated as normal.

In this cases, if a.b were either null or undefined, the expression would still throw as the ?. token only guards the value of a.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
Source: github.com

Q11: 
What is getters/setters in TypeScript?

Answer

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.

class foo {
  private _bar:boolean = false;

  get bar():boolean {
    return this._bar;
  }
  set bar(theBar:boolean) {
    this._bar = theBar;
  }
}

var myBar = myFoo.bar;  // correct (get)
myFoo.bar = true;  // correct (set)

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q12: 
What is a TypeScript Map file?

Answer

.map files are source map files that let tools map between the emitted JavaScript code and the TypeScript source files that created it. Many debuggers (e.g. Visual Studio or Chrome's dev tools) can consume these files so you can debug the TypeScript file instead of the JavaScript file.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q13: 
What is the difference between Classes and Interfaces in Typescript?

Answer

We use classes as object factories. A class defines a blueprint of what an object should look like and act like and then implements that blueprint by initialising class properties and defining methods. Classes are present throughout all the phases of our code.

Unlike classes, an interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once code is transpiled to its target language, it will be stripped from interfaces.

A class may define a factory or a singleton by providing initialisation to its properties and implementation to its methods, an interface is simply a structural contract that defines what the properties of an object should have as a name and as a type.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
Source: toddmotto.com

Q14: 
What is the difference between types String and string in TypeScript?

Answer
  • String is the JavaScript String type, which you could use to create new strings.
  • string is the TypeScript string type, which you can use to type variables, parameters and return values.

For example:

var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string = String("Hello World");

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q15: 
Are strongly-typed functions as parameters possible in TypeScript?

Problem

Consider the code:

class Foo {
    save(callback: Function) : void {
        //Do the save
        var result : number = 42; //We get a number from the save operation
        //Can I at compile-time ensure the callback accepts a single parameter of type number somehow?
        callback(result);
    }
}

var foo = new Foo();
var callback = (result: string) : void => {
    alert(result);
}
foo.save(callback);

Can you make the result parameter in save a type-safe function? Rewrite the code to demonstrate.

Answer

In TypeScript you can declare your callback type like:

type NumberCallback = (n: number) => any;

class Foo {
    // Equivalent
    save(callback: NumberCallback): void {
        console.log(1)
        callback(42);
    }
}

var numCallback: NumberCallback = (result: number) : void => {
    console.log("numCallback: ", result.toString());
}

var foo = new Foo();
foo.save(numCallback)

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
Does TypeScript supports function overloading?

Answer

Yes, TypeScript does support function overloading but the implementation is a bit different if we compare it to OO languages. We are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.

class Foo {
    myMethod(a: string);
    myMethod(a: number);
    myMethod(a: number, b: string);
    myMethod(a: any, b?: string) {
        alert(a.toString());
    }
}

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q17: 
Explain how and why we could use property decorators in TS?

Answer

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.

class CRUD {
    get() { }
    post() { }
 
    @admin
    delete() { }
 
    @owner
    put() { }
}

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q18: 
How TypeScript is optionally statically typed language?

Answer

TypeScript is referred as optionally statically typed, which means you can ask the compiler to ignore the type of a variable. Using any data type, we can assign any type of value to the variable. TypeScript will not give any error checking during compilation.

Consider:

var unknownType: any = 4;
unknownType = "Okay, I am a string";
unknownType = false; // A boolean.

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q19: 
How can you allow classes defined in a module to be accessible outside of the module?

Answer

Classes define in a module are available within the module. Outside the module you can’t access them.

module Vehicle {
    class Car {
        constructor (
            public make: string, 
            public model: string) { }
    }
    var audiCar = new Car("Audi", "Q7");
}
// This won't work
var fordCar = Vehicle.Car("Ford", "Figo");

As per above code, fordCar variable will give us compile time error. To make classes accessible outside module use export keyword for classes.

module Vehicle {
    export class Car {
        constructor (
            public make: string, 
            public model: string) { }
    }
    var audiCar = new Car("Audi", "Q7");
}
// This works now
var fordCar = Vehicle.Car("Ford", "Figo");

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q20: 
How to check the type of a variable or constant in TypeScript?

Answer

To check the type of a variable or a constant, you can use the typeof operator followed by the variable name in TypeScript.

Consider:

// a simple variable
let name = "John Doe";

// check if the "name" variable type is of "string"
if (typeof name === "string") {
    console.log("It is of 'string' type");
} else {
    console.log("It is not of 'string' type");
}

/* OUTPUT: */

// It is of 'string' type

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q21: 
How to choose between never, unknown, and any in TypeScript?

Answer
  • Use never in positions where there will not or should not be a value.
  • Use unknown where there will be a value, but it might have any type.
  • Avoid using any unless you really need an unsafe escape hatch.

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q22: 
Is that TypeScript code valid? Explain why

Problem

Consider:

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

interface Point3d extends Point {
    z: number;
}

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

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, you can use them in the same places you would be able to use interfaces.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q23: 
Is there a way to check for both null and undefined in TypeScript?

Answer

Using a juggling-check (it is where the type is juggled), you can test both null and undefined in one hit:

if (x == null) {

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (x === null) {

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q24: 
List a few rules of private fields in TypeScript

Answer
  • Private fields start with a # character. Sometimes we call these private names.
  • Every private field name is uniquely scoped to its containing class.
  • TypeScript accessibility modifiers like public or private can't be used on private fields.
  • Private fields can't be accessed or even detected outside of the containing class - even by JS users! Sometimes we call this hard privacy.

Consider:

class Person {
  #name: string;
  constructor(name: string) {
    this.#name = name;
  }
  greet() {
    console.log(`Hello, my name is ${this.#name}!`);
  }
}
let jeremy = new Person("Jeremy Bearimy");
jeremy.#name;
//     ~~~~~
// Property '#name' is not accessible outside class 'Person'
// because it has a private identifier.

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q25: 
What are different components of TypeScript?

Answer

There are mainly 3 components of TypeScript .

  1. Language – The most important part for developers is the new language. The language consist of new syntax, keywords and allows you to write TypeScript.
  2. Compiler – The TypeScript compiler is open source, cross-platform and open specification, and is written in TypeScript. Compiler will compile your TypeScript into JavaScript. And it will also emit error, if any. It can also help in concating different files to single output file and in generating source maps.
  3. Language Service – TypeScript language service which powers the interactive TypeScript experience in Visual Studio, VS Code, Sublime, the TypeScript playground and other editor.

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q26: 
What is Structural Typing?

Answer

The idea behind Structural Typing is that two types are compatible if their members are compatible.

For example:

  • In C# or Java, two classes named MyPoint and YourPoint, both with public int properties x and y, are not interchangeable, even though they are identical.
  • But in a structural type system, the fact that these types have different names is immaterial.
  • Because they have the same members with the same types, they are identical.

Consider:

interface Pet {
  name: string;
}
class Dog {
  name: string;
}
let pet: Pet;
// OK, because of structural typing
pet = new Dog();

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
Source: github.com

Q27: 
What is the difference between type and interface in TypeScript?

Answer

interface is a contract that the following properties should be there in an object. interface is not class. It is used when language does not support Multiple Inheritance. So interface can be a common structure between different classes.

Interfaces can be extended:

interface A {
    x: number;
}
interface B extends A {
    y: string;
}

Interfaces can also be augmented

interface C {
    m: boolean;
}
// ... later ...
interface C {
    n: number;
}

Type is like a variable declaration which holds the information of typeof other variable. type is like a superset of interfaces, classes, function signature, other types or even values (like type mood = 'Good' | 'Bad'). At the end type describes the possible structure or value of a variable:

type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;

So in general if you just have a plain object type, as shown in your question, an interface is usually a better approach. If you find yourself wanting to write something that can't be written as an interface, or want to just give something a different name, a type alias is better.


Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions

Q28: 
What is the fundamental difference between Optional Chaining (?.) and Non-null assertion operator (!) in TypeScript?

Answer

Non-null assertion operator:

  • Will not null guard your property chain.
  • It just tells TypeScript that the value is never going to be null.
  • But, if your value is indeed null, then your code will crash.

Optional chaining:

  • Will null check the property before it continues down the property chain, essentially guarding that value against being null or undefined.
  • If it finds that the property is null or undefined, then TypeScript will simply stop executing the property chain further and your code will proceed.
  • Optional chaining ?. is safer to use than non-null assertions !.

Having Tech or Coding Interview? Check 👉 91 TypeScript Interview Questions
Source: codeburst.io

Q29: 
Explain why that code is marked as WRONG?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q30: 
How would you overload a class constructor in TypeScript?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q31: 
In a?.b.c, if a.b is null, then a.b.c will evaluate to undefined, right?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q32: 
What is the difference between interface vs type statements?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q33: 
What is the difference between unknown and any type?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q34: 
Explain when to use declare keyword in TypeScript

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q35: 
Is it possible to generate TypeScript declaration files from JS library?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q36: 
What are Ambients in TypeScripts and when to use them?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...