,

Top 50 interview questions and answers for Type Script

Posted by

Top 50 interview questions and answers for Type Script

The Typescript is a powerfully typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft.

The Typescript is both a language and a set of tools. The Typescript is a typed superset of JavaScript amassed to JavaScript. In short, the Typescript is JavaScript plus some extra features.

Interview questions for Type Script:-

1. What are the main features of TypeScript?

  • Cross-Platform: The TypeScript compiler can be installed on any operating system such as Windows, macOS, and Linux.
  • ES6 Features: TypeScript includes most features of planned ECMAScript 2015 (ES6) such as Arrow functions.
  • Object-Oriented Language: TypeScript provides all the standard OOP features like classes, interfaces, and modules.
  • Static Type-Checking: TypeScript uses static typing and helps type checking at compile time. Thus, you can find compile-time errors while writing the code without running the script.
  • Optional Static Typing: TypeScript also allows optional static typing in case you are used to the dynamic typing of JavaScript.
  • DOM Manipulation: You can use TypeScript to manipulate the DOM for adding or removing client-side web page elements.

2. What are the benefits of using TypeScript?

TypeScript is more expressive, meaning it has less syntactical clutter.

Easy debugging due to advanced debugger that focuses on catching logical errors before compile-time

Static typing makes TypeScript easier to read and more structured than JavaScript’s dynamic typing.

Usable across platforms, in both client and server-side projects due to versatile transpiling.

3. What are the built-in data types of TypeScript?

Number type: It is used to represent number type values. All the numbers in TypeScript are stored as floating-point values.

The Typescript is a powerfully typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. The Typescript is both a language and a set of tools. The Typescript is a typed superset of JavaScript amassed to JavaScript. In short, the Typescript is JavaScript plus some extra features.

Interview questions for Type Script:-

1. What are the main features of TypeScript?

  • Cross-Platform: The TypeScript compiler can be installed on any operating system such as Windows, macOS, and Linux.
  • ES6 Features: TypeScript includes most features of planned ECMAScript 2015 (ES6) such as Arrow functions.
  • Object-Oriented Language: TypeScript provides all the standard OOP features like classes, interfaces, and modules.
  • Static Type-Checking: TypeScript uses static typing and helps type checking at compile time. Thus, you can find compile-time errors while writing the code without running the script.
  • Optional Static Typing: TypeScript also allows optional static typing in case you are used to the dynamic typing of JavaScript.
  • DOM Manipulation: You can use TypeScript to manipulate the DOM for adding or removing client-side web page elements.

2. What are the benefits of using TypeScript?

TypeScript is more expressive, meaning it has less syntactical clutter.

Easy debugging due to advanced debugger that focuses on catching logical errors before compile-time

Static typing makes TypeScript easier to read and more structured than JavaScript’s dynamic typing.

Usable across platforms, in both client and server-side projects due to versatile transpiling.

3. What are the built-in data types of TypeScript?

Number type: It is used to represent number type values. All the numbers in TypeScript are stored as floating-point values.

let identifier: number = value;
String type: It represents a sequence of characters stored as Unicode UTF-16 code. Strings are enclosed in single or double quotation marks.

let identifier: string = " ";
Boolean type: a logical binary switch that holds either true or false

let identifier: bool = Boolean value;
Null type: Null represents a variable whose value is undefined.
 let num: number = null;
Undefined type: an undefined literal that is the starting point of all variables.
let num: number = undefined;
Void type: The type assigned to methods that have no return value.
 let unusable: void = undefined;

4. What is the current stable version of TypeScript?

The current stable version is 4.2.3.

5. What is an interface in TypeScript?

Interfaces define a contract or structure for objects that use that interface.

An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

interface IEmployee {
    empCode: number;
    empName: string;
    getSalary: (number) => number; // arrow function
    getManagerName(number): string; 
}

6. What are modules in TypeScript?

Modules in TypeScript are a collection of related variables, functions, classes, and interfaces.

You can think of modules as containers that contain everything needed to execute a task. Modules can be imported to easily share code between projects.

module module_name{
class xyz{
export sum(x, y){
return x+y;
}
}

. How can you use TypeScript for the backend?

You can use Node.js with TypeScript to bring the benefits of TypeScript to backend work.

Simply install the TypeScript compiler into your Node.js by entering the following command:

npm i -g typescript 

8. What are Type assertions in TypeScript?

Type assertion in TypeScript works like typecasting in other languages but without the type checking or restructuring of data possible in languages like C# and Java. Type assertion has no impact on runtime and is used purely by the compiler.

Type assertion is essentially a soft version of typecasting that suggests the compiler see the variable as a certain type but does not force it into that mold if it’s in a different form.

TypeScript Syntax & Language Basics

9. How do you create a variable in TypeScript?

You can create variables in three ways: var, let, and const. var is the old style of fiercely scoped variables. You should avoid using var whenever possible because it can cause issues in larger projects.

var num:number = 1;

let is the default way of declaring variables in TypeScript, Compared to var, let reduces the number of compile-time errors and increases code readability.

let num:number = 1;

const creates a constant variable whose value cannot change. It uses the same scoping rules as let and helps reduce overall program complexity.

const num:number = 100;

10. You can use the super () function to call the constructor of the base class.

class Animal {
  name: string;
  constructor(theName: string) {
    this.name = theName;
  }
  move(distanceInMeters: number = 0) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
  }
}

class Snake extends Animal {
  constructor(name: string) {
    super(name);
  }
  move(distanceInMeters = 5) {
    console.log("Slithering...");
    super.move(distanceInMeters);
  }
}

11. Explain how to use TypeScript Mixins.

Mixins are essentially inheritance that works in the opposite direction. Mixins allow you to build new classes by combining simpler partial class setups from previous classes.

Instead of class A extending class B to gain its functionality, class B takes from class A and returns a new class with additional functionality.

12. How do you check null and undefined in TypeScript?

You can either use a juggle-check, which checks both null and undefined, and strict-check which returns true for values set to null and won’t evaluate true for undefined variables.

//juggle
if (x == null) {  
}  
var a: number;  
var b: number = null;  
function check(x, name) {  
    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');  
check(b, 'b');  

13. What are getters/setters in TypeScript? How do you use them?

Getters and setters are special types of methods that help you delegate different levels of access to private variables based on the needs of the program.

Getters allow you to reference a value but cannot edit it. Setters allow you to change the value of a variable but not see its current value. These are essential to achieve encapsulation.

For example, a new employer may be able to get the number of employees in the company but does not have permission to set the number of employees.

const fullNameMaxLength = 10;

class Employee {
  private _fullName: string = "";

  get fullName(): string {
    return this._fullName;
  }

  set fullName(newName: string) {
    if (newName && newName.length > fullNameMaxLength) {
      throw new Error("fullName has a max length of " + fullNameMaxLength);
    }

    this._fullName = newName;
  }
}

let employee = new Employee();
employee.fullName = "Bob Smith";

if (employee.fullName) {
  console.log(employee.fullName);
}

14. How do you allow classes defined in a module to be accessible outside of a module?

You can use the export keyword to open modules up for use outside the module.

module Admin {
  // use the export keyword in TypeScript to access the class outside
  export class Employee {
    constructor(name: string, email: string) { }
  }
  let alex = new Employee('alex', 'alex@gmail.com');
}

// The Admin variable will allow you to access the Employee class outside the module with the help of the export keyword in TypeScript
let nick = new Admin.Employee('nick', 'nick@yahoo.com');

15. How do we convert string to a number using Typescript?

Similar to JavaScript, You can use the parseInt or parseFloat functions to convert a string to an integer or float, respectively. You can also use the unary operator + to convert a string to the most fitting numeric type, “3” becomes the integer 3 while “3.14” becomes the float 3.14.

var x = "32";
var y: number = +x;

16. What is a ‘.map’ file, and why/how can you use it?

A map file is a source map that shows how the original TypeScript code was interpreted into usable JavaScript code. They help simplify debugging because you can catch any odd compiler behavior.

Debugging tools can also use these files to allow you to edit the underlying TypeScript rather than the emitted JavaScript file.

17. What are classes in TypeScript? How do you define them?

Classes represent the shared behaviors and attributes of a group of related objects.

For example, our class might be Student which all have the attendClass method. On the other hand, John is an individual instance of type Student and may have additional unique behaviors like attendExtracurricular.

You declare classes using the keyword class:

class Student {    
    studCode: number;    
    studName: string;    
    constructor(code: number, name: string) {    
            this.studName = name;    
            this.studCode = code;    
    }   

Keep practicing TypeScript.

Prepare for your interview with expert lessons and 400 hands-on coding environments. Educative’s text-based courses are easy to skim and focus on hirable skills to get you prepared in half the time.

18. How does TypeScript relate to JavaScript?

TypeScript is an open-source syntactic superset of JavaScript that compiles to JavaScript. All original JavaScript libraries and syntax still works but TypeScript adds additional syntax options and compiler features not found in JavaScript.

TypeScript can also interface with most of the same technologies as JavaScript, such as Angular and jQuery.

19. What is JSX in TypeScript?

JSX is an embeddable XML-like syntax that allows you to create HTML. TypeScript supports embedding, type checking, and compiling JSX directly to JavaScript.

20. What are the JSX modes TypeScript supports?

TypeScript has built-in support for preserve, react, and react-native.

preserve keeps the JSX intact for use in a subsequent transformation.

react does not go through a JSX transformation and instead emits react.createElement and outputs as a .js file extension.

react-native combines preserve and react in that it maintains all JSX and outputs as a .js extension.

21. How do you compile a TypeScript file?

You need to call the TypeScript compiler tsc to compile a file. You’ll need to have the TypeScript compiler installed, which you can do using npm.

npm install -g typescript

tsc <TypeScript File Name>

22. What scopes are available in TypeScript? How does this compare to JS?

Global Scope: defined outside of any class and can be used anywhere in the program.

Function/Class Scope: variables defined in a function or class can be used anywhere within that scope.

Local Scope/Code Block: variables defined in the local scope can be used anywhere in that block.

23. What are Arrow/lambda functions in TypeScript?

Fat arrow function is a shorthand syntax for defining function expressions of anonymous functions. It’s similar to lambda functions in other languages. The arrow function lets you skip the function keyword and write more concise code.

24. Explain Rest parameters and the rules to declare Rest parameters.

Rest parameters allow you to pass a varied number of arguments (zero or more) to a function. This is useful when you’re unsure how many parameters a function will receive. All arguments after the rest symbol … will be stored in an array. For example:

function Greet(greeting: string, ...names: string[]) {
    return greeting + " " + names.join(", ") + "!";
}
Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!"
Greet("Hello");// returns "Hello !"
The rest parameter must be the last on parameter definition and you can only have 1 rest parameter per function.

25. What are Triple-Slash Directives? What are some of the triple-slash directives?

Triple-slash Directives are single-line comments that contain an XML tag to use as compiler directives. Each directive signals what to load during the compilation process. Triple-slash Directives only work at the top of their file and will be treated as normal comments anywhere else in the file.

/// <reference path="..." /> is the most common directive and defines the dependency between files.
/// <reference types="..." /> is similar to path but defines a dependency for a package.
/// <reference lib="..." /> allows you to explicitly include the built-in lib file.

26. What does the Omit type do?

Omit is a form of utility type, which facilitates common type transformations. Omit lets you construct a type by passing a current Type and selecting Keys to be omitted in the new type.

Omit<Type, Keys>

For example:

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}

type TodoPreview = Omit<Todo, "description">;

27. How do you achieve function overloading in TypeScript?

To overload, a function in TypeScript, simply create two functions of the same name but have different argument/return types. Both functions must accept the same number of arguments. This is an essential part of polymorphism in TypeScript.

For example, you could make an add function that sums the two arguments if they’re numbers and concatenates them if they’re strings.

function add(a:string, b:string):string;
function add(a:number, b:number): number;
function add(a: any, b:any): any {
    return a + b;
}

add("Hello ", "Steve"); // returns "Hello Steve" 
add(10, 20); // returns 30 

28. How do you make all properties of an interface optional?

You can use the partial mapped type to easily make all properties optional.

29. When should you use the ‘unknown’ keyword?

You should use unknown if you don’t know which type to expect upfront but want to assign it later on, and the any keyword will not work.

30. What are decorators, and what can they be applied to?

A decorator is a special kind of declaration that lets you modify classes or class members all at once by marking them with the @<name> annotation. Each decorator must refer to a function that’ll be evaluated at runtime.

For example, the decorator @sealed would correspond to the sealed function. Anything marked with @sealed would be used to evaluate the sealed function.

function sealed(target) {

  // do something with ‘target’ …

}

They can be attached to:

Class declarations

  • Methods
  • Accessors
  • Properties

Parameters

31. How will you create a TypeScript object?

An object stores a set of key-value pairs. The syntax is as follows:

var name_of_obj= { key1: “val1”, key 2: ‘val2”, key3: function()}

32. Define static typing.

Static typing refers to a compiler having variables, parameters and object members that are recognizable at the compilation time. This helps in detecting early errors. Static typing is an important concept that supports many TypeScript Interview questions.

33. How is a typescript function called?

TypeScript is compiled into JavaScript using a JS function. The code of structure changes a bit during the process. If there are multiple modules, they become a part of the path calling the specific function.

34. Define super keyword.

Super keyword is a TypeScript keyword used by developers in expressions for base class properties reference and base class constructor. Only derived class constructors can make this call.

35. What are export and import keyword in TypeScript?

The export keyword is used to export any variable, function, and type alias. Import keyword is used to export declaration. Example: export * from ‘module.’

36. What is an optimal parameter in TypeScript?

The optimal parameter is used to declare optional parameters in a function. A parameter can be marked optional by using ‘?’ at the end of it. Example: par 2 is an optimal parameter.function functionName(par1: string, par2?: string) {

}

37. What is a Type of assertion?

Like a typecast in other languages, a type assertion performs no special checking. It is used purely by the compiler and has no runtime impact. However, TypeScript assumes that necessary special checks have been performed.

38. Is TypeScript an Optionally Statically Typed Language?

This is because the compiler ignores the variable type optionally. We can assign any value using any data type to the variable, and there is no error checking during compilation.

39. Tell us about TypeScript Definition Manager.

To work with external libraries in TypeScript, TypeScript definition files are needed. TypeScript Definition Manager is a package manager to install these definition files directly from a community-driven repository.

40. What is a type in TypeScript?

The type represents the value’s type that is being used in our programs. It supports the simplest unit of data such as strings, numbers, and additional types too.

41. Can TypeScript be used for the backend?

TypeScript can be generally used for backend applications by using Node.js and having additional safety that the language brings.

42. How will you check if a variable is null or undefined in TypeScript?

if(value) return true if value is not null, undefined, empty, false, 0 or NaN.

43. What are getters/setters?

Getters/setters intercept access to a member of the object. They give us a way of having finer-grained control over how a member accesses each object.

44. Name different components of TypeScript.

Language- the most critical part, compiler- open-source and cross-platform, language service- VS Code, Visual Studio, Sublime, etc.

45. Do TypeScript files need to be combined?

TypeScript is a language extension that the browser cannot interpret. Thus, it needs to be converted to JavaScript. This is called compiling.

46. How can a base class constructor be called from child class?

It can be called using super().

47. In which case should we use the interface and when should classes be used?

If you wish to create an instance of a custom object with the benefits of type checking, the class makes sense. If interfaces are not created, we have interfaces at our disposal, allowing us to virtually type-check code.

48. How can a class constant be implemented in TypeScript?

The const keyword cannot be used to declare class properties. A class member cannot have the ‘const’ keyword.

49. Name the object-oriented terms supported by TypeScript.

The supported terms are modules, classes, data types, interfaces and member functions.

50. Can classes in TypeScript be used in the same place as interfaces?

Yes, as classes create types, they can be used in the same place as the interfaces.

Here is a video link that will help you….

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x