
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialProgramming
4.7 Rating 70 Questions 45 mins read5 Readers

The values we assign to a variable in our program have a specific type, which is represented by types in TypeScript. In TypeScript we have support for a wide range of value types, including strings, Boolean, numbers, in addition to other types like enum, any, never, unknown and many more.
Declaring types explicitly in TypeScript is advantageous for a number of reasons. Types make code more readable and clearer, and they can also help your compiler identify issues that result from improper type assignments. Additionally, Types provide as an additional layer of documentation that might be useful when working in a team context.
To explicitly declare a type in TypeScript, you can append the ‘:’ after the variable name, following the Type of the assigned value. For example,
let stringVariable : string = "This is a string"; let numVariable : number = 2; let booleanVariable : boolean = true;
Object-oriented programming (OOP) is a computer programming style that organises software design around objects (or data), instead of functions and logic. An object is a data field with characteristics and behaviour.
Large, sophisticated, and actively updated or maintained programmes enjoy many benefits by using Object oriented programming style, for instance, large desktop applications, manufacturing system simulation software, and many more. Additionally, it makes the software easy to collaborate and distributed among small teams.
The OOP is based on four main principles; Encapsulation, Abstraction, Inheritance, and Polymorphism. This brings many benefits to the software in terms of reusability, scalability, and efficiency.
Yes, Typescript supports all the four principles Encapsulation, Abstraction, Inheritance, and Polymorphism of Object-oriented programming paradigm.
Encapsulation: Encapsulation is a technique for organising code and an essential element of object-oriented programming. According to this principle, an object contains all the critical information, with only a small subset of it being exposed outside.
Inheritance: Inheritance simply means that the Classes can reuse code from other classes. This enables developers to reuse common programming logic while still preserving a distinctive hierarchy. An inheritance chain and object model can be easily created with TypeScript.
Abstraction: Objects conceal any extraneous implementation code and only expose internal mechanisms that are necessary for the use of other objects. The derived class can typically extend the functionality of the base class. This approach makes it simpler for developers to introduce new features or make future modifications.
Polymorphism: When many classes from the same parent override the same functionality, this is known as polymorphism. Each newly created child class adds to the functionality of the parent class by implementing its own special properties or methods or by customising the base class's properties or methods to suit the needs of the child class.
Encapsulation is a technique for organising code and a key element of object-oriented programming. According to this principle, an object contains all the critical information, with only a small subset of it being exposed outside.
In other words, each object's implementation and state are kept secretly inside a defined class. This class is not accessible to other objects, nor do they have the power to modify it. Only a limited set of object members with public access are available outside the class. Thus, it creates an encapsulation for the private data.
For instance, let us create a Worker class, all the class members are public by default in TypeScript. But we can provide access modifiers (public, private, protected) to prevent other entity from accessing or modifying them outside the parent class scope.
class Worker { name: string; private _salary: number; constructor(name: string, salary: number) { this.name = name; this._salary = salary; } getSalary() : number { return this._salary; } } const john = new Worker("John", 50000); console.log(john._salary) // Property '_salary' is private and only accessible within class 'Worker'. console.log(john.getSalary()) //50000
We can also use getters and setters methods to achieve better encapsulation in Typescript. This data hiding provides greater program security and avoids unintended data corruption.
Functional programming means using functions to the best effect for creating clean and maintainable software. It is a declarative programming style, that puts more emphasis on “what to solve” in contrast to “how to solve”.
Functional programming highly depends upon the concept of Pure functions. A pure function is one whose outcomes depend only on the input variables and whose operation has no side effects to the outside world, aside from the return value.
Another important idea behind functional programming is immutability, i.e., avoid modifying the data outside the function, this is a way of avoiding side effects. In other words, only the function's return value should reflect the work that was done, and function input arguments should be copied, not changed.
Beyond the pure function ideal, functional programming depends on first class functions and higher order functions in actual coding practise.
You can join us and find the best online computer Programming courses to start your dream career.
This question is a regular feature in TyepScript questions, be ready to tackle it.
Generics allows programmers to pass types as parameters to another type, function, class, or other structures.
Making a generic component increases code flexibility, makes components reusable, and eliminates duplication by enabling the component to accept and enforce the types that are passed in when the component is used.
In TypeScript generics are written by writing the type variable inside the angle brackets in the format <T>, where T is a special kind of variable that denotes type. The type variable keeps track of the type that the user gives and works with that particular type only.
We can also use multiple types in the same generic structure, like <T, C, P>.
Example:
function addToCart<T>(product: T, cart: T[]): T[] {
return cart.push(product)
} This is a frequently asked interview question on TypeScript.
When TypeScript code is converted to JavaScript, all types and annotations are erased from the source code.
When JavaScript is being executed, the types you employ in TypeScript cannot be inspected at run-time. The types are only accessible during the compilation and/or transpiration process.
Given that JavaScript is still dynamically typed, it would be useless for V8 or other engines with internal optimization systems to include type-related comments in the code.
For instance, assume this is your TypeScript code:
let name: string = 'Robin';
After compilation TypeScript compiler emits the following code in a JavaScript file.
let name = 'Robin';
This holds true not only for basic types like number or string but also for any custom types you might develop. Furthermore, it indicates that some of your code is just discarded and is not getting used after being compiled into JavaScript. Therefore, the code given to the user is shorter, and all those interface lines are simply eliminated.
Expect to come across this popular question in TypeScript interview questions.
A module is a technique for creating groups for related entities, such as entities like variables, interfaces, classes, etc., in any combination.
Modules might be compared to containers that hold all the components required to complete a task. We can easily import/export modules to readily share code among projects.
The main reason modules are utilized their feature of inaccessibility, which prohibits the contained entities from being accessible from outside the module. Each entity in a module can only be executed from within its own scope, not from the global scope. This gives you a mechanism to restrict access to important variables and functions.
A must-know for anyone heading into a TypeScript interview, this question is frequently asked in TypeScript interview questions.
Getters and setters are unique methods that enable you to assign various levels of access to private variables based on the requirements of the code. These modifiers are significant if you are adding encapsulation to the class.
class Student{
private _studentId: number;
private _firstName: string;
private _lastName: string;
get studentId() {
return this._studentId;
}
set studentId(id: number) {
if (id <= 0 || id % 1 !== 0) {
throw new Error('The student ID is invalid');
}
this._studentId = id;
}
getFullName(): string {
return `${this._firstName} ${this._lastName}`;
}
} In the code, the _firstname, _lastname, and _studentId are private property and hence cannot be accessed directly outside the scope of the student class. The get and set keywords before the studentId() method define the getter and setter, respectively, for the studentId. The getter and setters do not have a private access modifier and hence can be called outside the scope of the Student class.
let raju = new Student()
raju._studentId = 12 // Property '_studentId' is private and only accessible within class 'Student'.
raju.studentId = 12
let id = raju.studentId;
console.log(id) // 12
It's no surprise that this one pops up often in TypeScript questions.
Enums allow us to create a collection of named constants. It is one of the few non-JavaScript type-level extensions available in TypeScript. We can consider enums as a simpler approach to providing more relevant names to constant values of a typescript program.
To create an enum in TypeScript, we use the keyword enum, followed by its name and the members. TypeScript provides both numeric as well as string-based approaches to define enums.
Example for Numeric approach:
enum Fruits{ APPLE, BANANA, GRAPES, ORANGE } let fruit: Fruits = Fruits.Banana;
By default, the enums begin to add numbering to the contained constants from 0. However, this default numbering behavior can be overridden by explicitly assigning the values to members inside an enum.
Example for string-based approach:
enum Fruits{
APPLE : ‘APPLE’
BANANA : ‘BANANA’
GRAPES : ‘GRAPES’
ORANGE : ‘ORANGE’
}
let fruit: Fruits = Fruits.BANANA; After compilation, the TypeScript compiler converts enums into plain JavaScript objects. Thus, as a result, it makes enums a more favorable choice compared to using multiple independent const variables, because it adds type safety and makes the code more readable.
This question is a regular feature in TypeScript advanced interview questions, be ready to tackle it.
Unlike JavaScript, we can create function overloading in a Typescript program. In function overloading, a program can have numerous functions with the same name but different parameters and return types. However, the total number of parameters for all the functions must be the same.
In function overloading, we write two or more overload signatures and one implementation signature.
An overload signature defines the parameter and return types of the function without the function body.
We add an implementation signature at the end. The implementation signature also has the parameter types and return type, but also a body that implements the function. The implementation signature type must be generic enough to include the overload signatures.
// Overload signature function doSomething(numA: number, numB: number): number; function doSomething(stringA: string, stringB: string): string[]; function doSomething(boolA: boolean, boolB: boolean): boolean[]; // Implementation signature function doSomething(a: unknown, b: unknown): unknown { if(typeof a === ‘number’) return a + b; if (type of a === ‘string’) return [a, b]; return a === b } doSomething(1, 2) // 3 doSomething(‘book’, ‘bag’) // [‘book’, ‘bag’] doSomething(false, true) // false doSomething(1, false) //Error
This is a frequently asked question in TypeScript interview questions.
Similar to interfaces, abstract classes define an object's contract but prevent direct object instantiation. An abstract class, as opposed to interfaces, can provide implementation details for one or more of its members.
In Typescript, we use the abstract modifier to define an abstract class. Typically, an abstract class has one or more abstract property declarations or methods.
In the implementation class that extends the abstract class, all the abstract members of the class must be defined. Moreover, in the constructor of the implementation class, the super() method must be called.
In the example, the abstract class Animal has one property and two methods. The talk() method is abstract, whereas the move() method has an implementation. All the classes that extend the Animal class have to provide their specific implementation for the write() method, e.g. Cat class and Dog class have their own talk() method. Whereas the non-abstract method move() of the abstract class Animal does not need to be implemented again for every class.
abstract class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
abstract talk(): void;
move(): void {
console.log(`${this.name} is moving`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
talk(): void {
console.log('Bark!!');
}
}
class Cat extends Animal {
constructor(name: string) {
super(name);
}
talk(): void {
console.log('Meow!!');
}
}
const pluto = new Dog('Pluto');
pluto.move(); // "Pluto is moving"
pluto.talk(); // "Bark!!"
const tom = new Cat('Tom');
tom.move(); // "Tom is moving"
tom.talk(); // "Meow!!" Expect to come across this popular question in TypeScript questions.
In TypeScript, constructor overloads work similarly to function overloading.
To create overloading for class constructors in TypeScript, you first define all the overloading constructors in layers. Immediately followed by the original constructor definition under the overloading constructors.
For example, let's create a class called Car with properties name having string type and yearMade having number type. The Car class also has a constructor method to initialize the value for the name and yearMade property fields,
class Car {
name: string;
yearMade: number;
constructor(name: string, yearMade: number) {
this.name = name;
this.yearMade = yearMade;
}
} Next to overload the class constructor with only yearMade parameter, we define the new constructor directly above the original constructor.
Moreover, all the constructors in an overloading class can have different parameters of different types, however, the total number of permanent parameters must remain the same. In other words, the Car class can have a minimum of one parameter thus, for the constructor that takes more than one parameter, we shall make the other parameters optional. Moreover, the type for all the permanent parameters must be generic enough, hence use the type “any” for the parameters in the original constructor.
class Car {
name: string;
yearMade: number;
// constructor overload here
constructor(yearMade: number);
constructor(nameOrYear: any, yearMade?: any) {
this.name = nameOrYear;
this.yearMade = yearMade;
}
} A must-know for anyone heading into a TypeScript interview, this question is frequently asked in TypeScript interview.
Inheritance is an important concept in object-oriented programming, specifically for polymorphism and code reusability. There are two main keywords that TypeScript uses for inheritance – extends and implements.
When a class extends to another class, all the members from the parent class are transferred to the child class. Any of its parent's existing properties and methods can be overridden, and new ones can be added.
When a class implements another class or interface, the class must implement all the members from the implemented class or interface. The implements keyword serves as an agreement that the implemented class has to follow. TypeScript's job is to make sure that the class maintains the exact shape similar to the class or interface it is implementing.
Here is a simple example to explain both.
class User { name: string; userId: number; greet: () => void } // Max will inherit the name and userId from the User class class Max extends User {} // this will result in an error as Rahul doesn't have all the properties that the User class has class Rahul implements User {} // This is valid as Rahul satisfies the contract (i.e. contains all the member properties and methods) specified by the User class class Rahul implements User { name = 'Rahul'; userId = 19724 greet = function () { console.log(`Hello ${this.name}`) } }
It's no surprise that this one pops up often in TypeScript interview questions.
A decorator is a special declaration used to supplement existing code with annotations and metadata to your program syntax. They are used in a declarative manner and require enabling the experimentalDecorators either on the command line or in your tsconfig.json compiler function in order to utilize them.
A class declaration, method, accessor, property, or argument can all be decorated with the decorator declaration type. Decorators take the form @expression, where this sign is written as a prefix to decorators when an expression should evaluate a function. When the decorated declaration is called at runtime, the information from the decorated declaration and this function will both be called.
When we put multiple decorators to a single declaration syntax, their evaluation is similar to the composition of functions present in mathematics. For instance, in the code below, the @first and @second decorators create a composite function similar to (f ∘ g)(x)is equivalent to f(g(x)) in mathematics.
The compiler evaluates these decorators in the following order:
function first() {
console.log("first");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("first(): called");
};
}
function second() {
console.log("second");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("second(): called");
};
}
class Foo {
@first()
@second()
method() {}
}