Codementor Events

20 Essential TypeScript Interview Questions and Answers in 2018

Published Aug 01, 2018Last updated Oct 02, 2018

20 TypeScript Interview Questions and Answers in 2018TypeScript starts from the same syntax and semantics that millions of JavaScript developers know today. TypeScript offers support for the latest and evolving JavaScript features, including those from ECMAScript 2015 and future proposals, like async functions and decorators, to help build robust components. Follow throught and read 20 essential TypeScript Interview Questions And Answers compiled by FullStack.Cafe editorial team.

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

Topic: TypeScript
Difficulty: ⭐

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.

🔗 Source: stackoverflow.com

Q2: Explain generics in TypeScript

Topic: TypeScript
Difficulty: ⭐

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

🔗 Source: basarat.gitbooks.io

Q3: Does TypeScript support all object oriented principles?

Topic: TypeScript
Difficulty: ⭐⭐

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.

🔗 Source: jonathanmh.com

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

Topic: TypeScript
Difficulty: ⭐⭐

Just use:

if (value) {
}

It will evaluate to true if value is not:

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

TypesScript includes JavaScript rules.

🔗 Source: stackoverflow.com

Q5: How to implement class constants in TypeScript?

Topic: TypeScript
Difficulty: ⭐⭐

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

🔗 Source: stackoverflow.com

Q6: What is a TypeScript Map file?

Topic: TypeScript
Difficulty: ⭐⭐

.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.

🔗 Source: stackoverflow.com

Q7: What is getters/setters in TypeScript?

Topic: TypeScript
Difficulty: ⭐⭐

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)

🔗 Source: typescriptlang.org

Q8: Could we use TypeScript on backend and how?

Topic: TypeScript
Difficulty: ⭐⭐

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"
  }
}
tsc
node build/index.js

🔗 Source: jonathanmh.com

Q9: What are different components of TypeScript?

Topic: TypeScript
Difficulty: ⭐⭐⭐

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.

🔗 Source: talkingdotnet.com

Q10: Is that TypeScript code valid? Explain why.

Topic: TypeScript
Difficulty: ⭐⭐⭐

Consider:

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

🔗 Source: typescriptlang.org

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

Topic: TypeScript
Difficulty: ⭐⭐⭐

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() { }
}

🔗 Source: www.sitepen.com

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

Topic: TypeScript
Difficulty: ⭐⭐⭐

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.

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)

🔗 Source: stackoverflow.com

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

Topic: TypeScript
Difficulty: ⭐⭐⭐

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");

🔗 Source: http://www.talkingdotnet.com

Q14: Does TypeScript supports function overloading?

Topic: TypeScript
Difficulty: ⭐⭐⭐

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());
    }
}

🔗 Source: typescriptlang.org

Q15: Explain why that code is marked as WRONG?

Topic: TypeScript
Difficulty: ⭐⭐⭐⭐

/* WRONG */
interface Fetcher {
    getObject(done: (data: any, elapsedTime?: number) => void): void;
}

Don’t use optional parameters in callbacks unless you really mean it. This code has a very specific meaning: the done callback might be invoked with 1 argument or might be invoked with 2 arguments. The author probably intended to say that the callback might not care about the elapsedTime parameter, but there’s no need to make the parameter optional to accomplish this – it’s always legal to provide a callback that accepts fewer arguments.

🔗 Source: typescriptlang.org

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

Topic: TypeScript
Difficulty: ⭐⭐⭐⭐

TypeScript allows you to declare overloads but you can only have one implementation and that implementation must have a signature that is compatible with all overloads. Some techniques for constructor overloading are:

  • with an optional parameter as in
class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor();
    constructor(obj: IBox); 
    constructor(obj?: any) {    
        this.x = obj && obj.x || 0
        this.y = obj && obj.y || 0
        this.height = obj && obj.height || 0
        this.width = obj && obj.width || 0;
    }   
}
  • default parameters
class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj : IBox = {x:0,y:0, height:0, width:0}) {    
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }   
}
  • additional overloads as static factory methods
class Person {
    static fromData(data: PersonData) {
        let { first, last, birthday, gender = 'M' } = data 
        return new this(
            `${last}, ${first}`,
            calculateAge(birthday),
            gender
        )
    }

    constructor(
        public fullName: string,
        public age: number,
        public gender: 'M' | 'F'
    ) {}
}

interface PersonData {
    first: string
    last: string
    birthday: string
    gender?: 'M' | 'F'
}


let personA = new Person('Doe, John', 31, 'M')
let personB = Person.fromData({
    first: 'John',
    last: 'Doe',
    birthday: '10-09-1986'
})
  • using union types
class foo {
    private _name: any;
    constructor(name: string | number) {
        this._name = name;
    }
}
var f1 = new foo("bar");
var f2 = new foo(1);

🔗 Source: stackoverflow.com

Q17: What is the difference between “interface vs type” statements?

Topic: TypeScript
Difficulty: ⭐⭐⭐⭐

interface X {
    a: number
    b: string
}

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

Unlike an interface declaration, which 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.

By using type instead of interface the following capabilities are lost:

  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

🔗 Source: stackoverflow.com

Q18: Explain when to use “declare” keyword in TypeScript

Topic: TypeScript
Difficulty: ⭐⭐⭐⭐⭐

The TypeScript declare keyword is used to declare variables that may not have originated from a TypeScript file.

For example, lets imagine that we have a library called myLibrary that doesn’t have a TypeScript declaration file and have a namespace called myLibrary in the global namespace. If you want to use that library in your TypeScript code, you can use the following code:

declare var myLibrary;

The type that the TypeScript runtime will give to myLibrary variable is the any type. The problem here is that you won’t have Intellisense for that variable in design time but you will be able to use the library in your code. Another option to have the same behavior without using the declare keyword is just using a variable with the any type:

var myLibrary: any;

Both of the code examples will result in the same JavaScript output but the declare example is more readable and expresses an ambient declaration.

🔗 Source: stackoverflow.com

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

Topic: TypeScript
Difficulty: ⭐⭐⭐⭐⭐

Ambients or Ambient declarations are a way of telling the TypeScript compiler that the actual source code exists elsewhere. Ambient declarations help to seamlessly integrate other js libraries into TypeScript.

Ambient declarations are by convention kept in a type declaration file with d.ts extension. The syntax for declaring ambient variables or modules will be as following:

declare module Module_Name {
}

The ambient files should be referenced in the client TypeScript file as shown

/// <reference path=" Sample.d.ts"></reference>

🔗 Source: stackoverflow.com

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

Topic: TypeScript
Difficulty: ⭐⭐⭐⭐⭐

JavaScript doesn’t always contain enough type information for the TypeScript compiler to infer the structures in your code - so automatically generating a definition based on JavaScript is rarely an option but you could try:

  • Microsoft/dts-gen - The official starting point Microsoft uses when creating types

  • dtsmake - This one looks very promising. It depends on Ternjs which some editors use to provide autocomplete for JS code.

🔗 Source: stackoverflow.com

Thanks 🙌 for reading and good luck on your interview!
Check more FullStack Interview Questions & Answers on 👉 www.fullstack.cafe

Discover and read more posts from Alex Ershov
get started