Typescript Interview Questions for Freshers
Typescript Interview Questions for Experienced
Beginner Level TypeScript Interview Questions
Intermediate Level TypeScript Interview Questions
Advanced Level TypeScript Interview Questions
What is TypeScript and how is it different from JavaScript ?
TypeScript is a statically typed superset of JavaScript. It is a language that builds upon JavaScript by adding optional static typing and class-based object-oriented programming. TypeScript allows developers to catch errors at compile-time rather than runtime and also provides a better understanding of how the code will behave, improving maintainability and readability.
What are the primitive types in TypeScript ?
Primitive types in TypeScript include number, string, boolean, symbol, and bigint.
Explain how the arrays work in TypeScript ?
Arrays in TypeScript can be declared as a collection of elements with a specific data type. The syntax for declaring an array is as follows:
let list: Array<string> = ['apple', 'banana', 'orange'];
Or you can use a shorthand syntax to declare the same array:
let list: string[] = ['apple', 'banana', 'orange'];
What is any type, and when to use it ?
The any type is a way to tell TypeScript that a variable can hold any type of value. This is useful when you are working with third-party libraries or when you don’t know the type of an expression. However, it can also lead to type safety issues if not used carefully, as TypeScript won’t be able to catch any errors related to the type of a variable declared with the any type.
What is void, and when to use the void type ?
The void type represents the absence of a value. It is used as the return type of functions that don’t return any value. For example:
function sayHello(): void { console.log('Hello!'); }
What is an unknown type, and when to use it in TypeScript ?
The unknown type is a type-safe alternative to any. Unlike any, values of type unknown cannot be used before they are type-checked. This means that you can’t call methods or access properties of an unknown type variable without first checking its type. The unknown type is useful in situations where you are expecting a value to be of a specific type, but you want to ensure that you check its type before using it.
What are the different keywords to declare variables in TypeScript ?
In TypeScript, there are two keywords to declare variables: let and const. let allows you to declare a variable that can be reassigned, while const declares a variable that can’t be changed after it’s been assigned. Here’s an example:
let name: string = 'John'; name = 'Jane'; // allowed const lastName: string = 'Doe'; lastName = 'Smith'; // not allowed
Provide the syntax of a function with the type annotations ?
Syntax of a function with type annotations:
function addNumbers(num1: number, num2: number): number { return num1 + num2; }
How to create objects in TypeScript ?
Creating objects in TypeScript:
interface User { name: string; age: number; } const user: User = { name: 'John Doe', age: 35 };
How to specify optional properties in TypeScript ?
Specifying optional properties in TypeScript:
interface User { name: string; age?: number; } const user: User = { name: 'John Doe' };
Explain the concept of null and its use in TypeScript ?
Concept of null and its use in TypeScript:
In TypeScript, null is a value that represents the absence of a value. It is used when a value is intentionally left undefined. For example:
let user: User | null = null;
What is undefined in TypeScript ?
Undefined in TypeScript:
In TypeScript, undefined is a value that indicates that a variable has not been assigned a value. For example:
let user: User | undefined;
Explain the purpose of the never type in TypeScript ?
Purpose of the never type in TypeScript:
The never type in TypeScript represents a value that is never returned. It is used in situations where a function is expected to throw an error or when a value is never meant to be reached. For example:
function throwError(): never { throw new Error('An error occurred'); }
Explain how enums work in TypeScript ?
Enums in TypeScript: Enums in TypeScript are a way to define a set of named constants. Each constant is given a unique number. For example:
enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } let day: DaysOfWeek = DaysOfWeek.Monday;
In this example, DaysOfWeek is the name of the enum and each day of the week is a constant with a unique number. The constant Monday has a value of 0, Tuesday has a value of 1, and so on.
What are Object-Oriented Principles supported by TypeScript ?
Object-Oriented Principles supported by TypeScript are:
- Encapsulation: This principle allows you to hide the implementation details of a class and provide a public interface to interact with it. In TypeScript, you can achieve this by using access modifiers like public, private, and protected.
- Inheritance: TypeScript supports inheritance, which allows you to create a new class based on an existing class and extend its functionality.
- Polymorphism: TypeScript supports polymorphism through its support for interfaces and abstract classes. You can use these to define a common interface for a group of classes and then override their methods in each individual class.
- Abstraction: TypeScript supports abstraction through its support for abstract classes, which allow you to define a class that cannot be instantiated but can be extended.
What is the typeof operator ? How is it used in TypeScript ?
The typeof operator is a type operator in TypeScript that returns the data type of a variable or expression. It is used to determine the type of an object at runtime. The typeof operator is used in TypeScript to determine the type of an object when checking the type of a variable or an expression. The syntax of the typeof operator is:
typeof variable_name
Example:
let x: number = 10;
console.log(typeof x); // outputs “number”
What are Objects in TypeScript ?
Objects in TypeScript: In TypeScript, objects are used to store and manipulate data. Objects can be created using object literals, class constructors, and object factories. Objects in TypeScript can have properties and methods and can be used to store and manipulate data in a more structured manner.
What are Rest Parameters in Typescript ?
Rest Parameters in Typescript: Rest parameters are a way to gather the remaining arguments passed to a function into an array. They are denoted by using three dots (…) before the parameter name in the function definition. The rest parameters allow a function to accept an indefinite number of arguments.
What are the rest parameters and arguments in TypeScript ?
Rest Parameters and Arguments in TypeScript: In TypeScript, rest parameters are defined in a function definition by using the spread operator (…). The rest parameters are then used as an array in the function body. The rest parameters are usually used to gather remaining arguments that were not explicitly defined in the function definition.
How to Install Typescript ?
How to Install Typescript: To install Typescript, you need to have Node.js installed on your system. Then, you can use the npm package manager to install Typescript by running the following command: npm install -g typescript
What is parameter destructuring ?
Parameter Destructuring: Parameter destructuring is a feature in TypeScript that allows you to extract values from objects or arrays and assign them to separate variables. This can simplify the code by reducing the amount of code needed to extract values from objects or arrays.
How to define a TypeScript class which has an index signature ?
To define a TypeScript class with an index signature, you can use the following syntax:
class MyClass {
[key: string]: any;
}
This defines a class with an index signature, meaning that properties can be accessed using an index rather than a property name.
How to exclude property from type in TypeScript ?
To exclude a property from a type in TypeScript, you can use the following syntax:
type MyType = {
prop1: string;
prop2: number;
}
type ExcludedProperties = Exclude<keyof MyType, “prop2”>;
This creates a new type, ExcludedProperties, that only includes the prop1 property from the MyType type.
Explain what is never datatype in TypeScript ?
The never data type in TypeScript represents the values that never occur. This is a type that can be used in a function that never returns a value. It is the opposite of the any data type, which represents any type.
Explain when to use declare keyword in TypeScript ?
The declare keyword is used in TypeScript to declare variables that have already been defined in another part of the code. This is useful when working with third-party libraries or code written in another language. The declare keyword tells TypeScript that the variable is already defined, so it does not need to generate code for it.
How the never datatype can be useful ?
The never data type can be useful in situations where you want to enforce that a function or expression never returns a value. This can help prevent bugs and improve code quality by catching errors early in the development process.
Explain the TypeScript class syntax ?
TypeScript Class Syntax:
In TypeScript, a class is a blueprint for creating objects (instances) of a particular type. The class syntax in TypeScript is similar to that in other object-oriented programming languages. Here is an example:
class MyClass { // class members, such as properties and methods property1: type1; method1(): void { // method implementation } }
Explain Classes in TypeScript ?
Classes in TypeScript:
Classes in TypeScript allow you to define the structure and behavior of objects in a more organized and reusable manner. They allow you to define instance variables, methods, and constructor. Here is an example:
class Car { constructor(public make: string, public model: string) { } drive() { console.log(`Driving my ${this.make} ${this.model}`); } } const myCar = new Car('Toyota', 'Camry'); myCar.drive();
Explain the arrow function syntax in TypeScript ?
Arrow Function Syntax in TypeScript:
Arrow functions, also known as “fat arrow” functions, provide a shorthand for writing anonymous functions in TypeScript. Arrow functions preserve the this keyword from the surrounding code and provide a more concise syntax. Here is an example:
const myFunction = (input1: type1, input2: type2) => { // function implementation };
Explain Arrays in TypeScript ?
Arrays in TypeScript:
Arrays in TypeScript are used to store multiple values in a single variable. The type of values stored in an array can be specified using type annotations. Here is an example:
const myArray: Array<string> = ['value1', 'value2', 'value3'];
Provide the syntax for optional parameters in TypeScript ?
Syntax for Optional Parameters in TypeScript:
Optional parameters in TypeScript can be defined by adding a ? character to the end of the parameter name. Optional parameters are useful when you want to provide default values for parameters that may not be supplied when the function is called. Here is an example:
function myFunction(requiredParam: string, optionalParam?: string) { if (optionalParam) { console.log(optionalParam); } else { console.log('Optional parameter not provided.'); } }
List the Applications of TypeScript ?
Applications of TypeScript:
Web Development
Enterprise-level applications
Cross-platform Development
Building libraries and frameworks
Building large-scale applications with a team of developers.
What is the purpose of the tsconfig.json file ?
Purpose of tsconfig.json file:
The tsconfig.json file is a configuration file in TypeScript that specifies the compiler options for the TypeScript files in a project. It helps to manage the settings and configurations of a TypeScript project, such as the target JavaScript version, source files, output paths, etc.
Explain Loops in Typescript ?
Loops in TypeScript:
Loops are used in TypeScript to execute a block of code repeatedly for a specified number of times or until a particular condition is met. The following are the types of loops supported in TypeScript:
for loop
for…in loop
for…of loop
while loop
do…while loop
What is the use of the tsconfig.json file ?
Use of tsconfig.json file:
The tsconfig.json file helps to configure the TypeScript compiler options, including:
Setting the root directory of the project.
Specifying the TypeScript version to use.
Configuring the ECMAScript target version.
Setting the module code generation.
Enabling/disabling strict type checking.
Specifying the files and directories to include or exclude.
Explain the different variants of the for loop in TypeScript ?
Different variants of the for loop in TypeScript:
The for loop: This is the standard loop in TypeScript used to execute a block of code a specified number of times.
The for…in loop: This loop is used to iterate over the properties of an object.
The for…of loop: This loop is used to iterate over the elements of an array or a string.
What is JSX ?
JSX:
JSX is a syntax extension for JavaScript that allows for the mixing of HTML-like code within JavaScript code. It is often used with React to build user interfaces. TypeScript has full support for JSX, which means you can use it with TypeScript to build dynamic and interactive web applications.
Explain the symbol type in TypeScript ?
Symbol Type: In TypeScript, a symbol is a unique identifier and can be used as an object property or index. The Symbol type is used to create symbols in TypeScript. Symbols are often used to create unique object properties that can be used as a key in a map or a property in an object.
What are import and export keywords in TypeScript ?
Import and Export Keywords: The import and export keywords are used to manage the modules in TypeScript. The import keyword is used to import values from other modules and make them available in the current module. The export keyword is used to make values from the current module available to other modules.
Explain how optional chaining works in TypeScript ?
Optional Chaining: Optional chaining is a feature in TypeScript that allows you to access properties of an object or elements of an array without raising an error if the property or element is undefined or null. You can access properties or elements by using the ?. operator.
Provide the TypeScript syntax to create function overloads ?
Function Overloads: Function overloads in TypeScript allow you to declare multiple functions with the same name but with different signatures. The correct function to be called is determined at compile-time based on the type of arguments passed to the function. The syntax to create function overloads in TypeScript is as follows:
function sum(a: number, b: number): number; function sum(a: string, b: string): string; function sum(a: any, b: any): any { return a + b; }
What is Type Erasure in TypeScript ?
Type Erasure: Type erasure is the process of removing type information from a TypeScript program after it has been compiled to JavaScript. The type information is used by the TypeScript compiler to check for type compatibility and other type-related errors, but it is not needed at runtime.
What is meant by type inference ?
Type Inference: Type inference is the process by which the TypeScript compiler can automatically determine the type of a value based on the context in which it is used. For example, if you assign a string value to a variable, the TypeScript compiler can infer that the type of the variable is string. Type inference makes it easier to use TypeScript by reducing the amount of type annotations you need to write.
How do we create an enum with string values ?
Creating an enum with string values:
In TypeScript, enums are used to define a set of named constants. By default, enums have numeric values, but you can also give them string values. Here’s an example:
enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE" }
What is meant by contextual typing ?
Contextual typing:
Contextual typing is a feature in TypeScript where the type of a value is automatically inferred based on its context. For example:
let x = "hello"; x = 123; // Error, Type '123' is not assignable to type 'string'
In this example, the type of x is automatically inferred as string based on the value assigned to it.
What is the purpose of noImplicitAny ?
Purpose of noImplicitAny:
The noImplicitAny compiler option in TypeScript is used to enforce strict type checking. When set to true, the compiler will generate an error if it encounters an expression with an implicit any type. This helps to catch type-related bugs early in the development process and improves the overall quality of the code.
What are getters/setters ?
etters/Setters:
Getters and setters are special methods in object-oriented programming languages that provide access to an object’s properties. A getter is a method used to retrieve the value of a property, while a setter is a method used to set the value of a property. In TypeScript, getters and setters are defined using the get and set keywords.
Here’s an example:
class Person { private _name: string; get name(): string { return this._name; } set name(value: string) { this._name = value; } }
What is an interface ?
Interface:
In TypeScript, an interface is a structure that defines the shape of an object. It specifies the names, types, and values of the properties that an object must have. Interfaces are used to define a contract for a class or a function. They allow you to define a structure that your code must adhere to, helping to catch bugs early in the development process and improving the overall quality of the code.
Here’s an example:
interface Person { name: string; age: number; } const person: Person = { name: "John Doe", age: 30 };
What is Lambda/Arrow function ?
Lambda/Arrow function:
Lambda functions, also known as Arrow functions, are a concise way to declare anonymous functions in TypeScript and JavaScript. They are represented by the “=>” syntax, and are used to define functions in a more concise and expressive way.
Example:
let add = (a: number, b: number) => a + b;
Explain the various ways to control member visibility in TypeScript ?
Member visibility in TypeScript:
In TypeScript, there are three keywords that can be used to control member visibility: “public”, “private”, and “protected”.
“public” members can be accessed from anywhere within the code. This is the default visibility.
“private” members can only be accessed from within the class where they are declared.
“protected” members can be accessed from the class where they are declared and from any subclasses that extend that class.
Example:
class Foo { private x: number; protected y: number; public z: number; }
What is Type assertions in TypeScript ?
Type assertions in TypeScript:
Type assertions are a way to override the type inference of TypeScript and tell the compiler what type a value is. They are represented by angle brackets (<>) or an “as” keyword.
Example:
let message; message = 'Hello World'; let messageLength = (<string>message).length; let messageLength2 = (message as string).length;
Does TypeScript support static classes ? If not, why ?
Static classes in TypeScript:
No, TypeScript does not support static classes. However, it does allow us to create static methods within a class.
What is a TypeScript Map file ?
TypeScript Map file:
A TypeScript map file is a file that maps the compiled JavaScript code back to the original TypeScript source code. It can be generated using the “sourceMap” compiler option and is useful for debugging the original TypeScript code when working with the compiled JavaScript code. The map file allows us to see the original TypeScript code, even when we are looking at the compiled JavaScript code in a browser’s dev tools.
What are abstract classes ? When should you use one ?
Abstract classes:
Abstract classes are classes that cannot be instantiated on their own and are meant to be a base class for other classes. An abstract class can contain both abstract and non-abstract methods. Abstract methods are methods that have no implementation and must be overridden by the derived class.
You should use abstract classes when you want to define some common behavior in a base class that can be shared across multiple derived classes.
What are all the JSX modes TypeScript supports ?
JSX Modes in TypeScript:
TypeScript supports the following JSX modes:
preserve: The JSX code will be preserved as-is in the output file.
react: The JSX code will be transformed to JavaScript, with the react JSX optimizations.
react-native: The JSX code will be transformed to JavaScript, with the react-native JSX optimizations.
What are anonymous functions ? Provide their syntax in TypeScript ?
Anonymous Functions:
An anonymous function is a function without a name. In TypeScript, anonymous functions can be defined using the following syntax:
(args: type) => returnType
Explain Enum in TypeScript ?
Enum in TypeScript:
Enum is a way of giving more friendly names to sets of numeric values. In TypeScript, you can define enums using the enum keyword. For example:
enum Color { Red, Green, Blue }
What are union types in TypeScript ?
Union Types in TypeScript:
Union types in TypeScript allow you to specify multiple possible types for a single value. The syntax for union types is to use the pipe | operator to separate each type. For example:
let unionVariable: string | number;
In the above example, unionVariable can be either a string or a number.
What are intersection types ?
Intersection types are types that combine multiple types into one. They are denoted by the ‘&’ symbol and are used to represent a value that has all the properties and methods of the intersected types.
What are type aliases ? How do you create one ?
Type aliases are a way to create a new name for an existing type. They are created using the ‘type’ keyword, followed by the new name and the original type. For example, type MyString = string;
What is tsconfig.json file ?
tsconfig.json is a configuration file for TypeScript projects that specifies compiler options, file inclusion and exclusion patterns, and other settings.
Explain the tuple types in TypeScript ?
Tuple types are a specific type of array in TypeScript that have a fixed length and a specific type for each element. They are defined using square brackets with the types of the elements separated by commas, such as [string, number, boolean].
What are Mixins ?
Mixins are a way to combine multiple classes into a single class that has the properties and methods of all the constituent classes. They are created using a combination of class inheritance and object composition, and are commonly used to add functionality to classes without creating deep inheritance hierarchies.
Explain how tuple destructuring works in TypeScript ?
Tuple destructuring in TypeScript allows you to unpack values from a tuple and assign them to separate variables. This can be done by enclosing the variable names in square brackets on the left-hand side of an assignment statement, and assigning the tuple to the right-hand side. For example:
let tuple: [string, number] = ['foo', 42]; let [str, num] = tuple; console.log(str); // outputs 'foo' console.log(num); // outputs 42
How can you debug a TypeScript file ?
To debug a TypeScript file, you can use the built-in debugging support in your code editor or IDE. You can set breakpoints in your code, step through it line by line, inspect variables and expressions, and view the call stack. You can also use console.log statements to output debug information to the console.
What are type assertions in TypeScript ?
Type assertions in TypeScript allow you to override the inferred or declared type of a value. This can be useful in cases where you know the actual type of a value but TypeScript cannot infer it. Type assertions can be done using the as keyword or the angle bracket syntax. For example:
let str: any = 'foo'; let strLength: number = (str as string).length;
What are the steps to include Type Definition File ?
To include a Type Definition File in your TypeScript project, you can use the /// <reference path=”path/to/file.d.ts” /> directive at the top of your TypeScript file. You can also install type definition files using a package manager like npm.
How to enforce strict null checks in TypeScript ?
To enforce strict null checks in TypeScript, you can enable the strictNullChecks compiler option in your tsconfig.json file. This will make TypeScript more stringent in its handling of null and undefined values, and will help prevent errors related to null and undefined values. For example:
{ "compilerOptions": { "strictNullChecks": true } }
What is namespace in Typescript and how to declare it ?
In TypeScript, namespaces provide a way to organize code into logical groups and prevent naming collisions. To declare a namespace, you use the namespace keyword followed by the namespace name.
How to make object properties immutable in TypeScript ? (hint: readonly)
To make object properties immutable in TypeScript, you can use the readonly keyword. For example, to make a property x of an object immutable, you can declare it like this: readonly x: number.
What is a type declaration file ?
A type declaration file is a file with a .d.ts extension that contains type information for existing JavaScript code. It allows TypeScript to understand the types used in the code and provides better editor support and error checking.
Describe ‘as’ syntax in TypeScript ?
The as syntax in TypeScript is used for type assertions, which allow you to tell the compiler that a value has a certain type even if the compiler can’t infer it from the code. For example, you can use the as syntax like this: const x: any = “hello”; const y: string = x as string;
What are triple-slash directives ?
Triple-slash directives are special comments in TypeScript that provide additional information to the compiler. They start with three slashes (///) and can be used to reference external libraries or files, provide additional type information, and more.
What is meant by Type Inference ?
Type inference is a feature of some programming languages that allows the compiler to deduce the data types of variables and expressions based on their usage within the program, without the need for explicit type annotations.
Explain the purpose of the ‘in’ operator ?
The ‘in’ operator in JavaScript is used to check if a specified property exists in a given object. It returns true if the property exists and false otherwise.
What is JSX in TypeScript ?
JSX is an extension to the JavaScript language that allows developers to write HTML-like syntax within their JavaScript code. When used in conjunction with TypeScript, JSX can be type-checked to ensure that the components being rendered are of the correct type.
What are the ‘implements’ clauses in TypeScript ?
The ‘implements’ clause in TypeScript is used to indicate that a class implements a particular interface. This allows the compiler to verify that the class implements all the methods and properties defined in the interface.
What are the Disadvantages of TypeScript ?
Some potential disadvantages of TypeScript include the added complexity of type annotations, the need to maintain and update type definitions, and the potential for increased build times and decreased runtime performance. Additionally, some developers may prefer the flexibility of dynamic typing in other languages.
What are string literal types ?
String literal types are a type of string in TypeScript that can only have a specific set of values, which are defined at the time of declaration.
What are the Components of TypeScript ?
The components of TypeScript include the TypeScript language itself, the TypeScript Compiler, the TypeScript Language Service, and the TypeScript Language Server Protocol.
What are template literal types ?
Template literal types are a new feature in TypeScript that allow for the creation of more complex types by using string templates as type constraints.
What are the Recent Advancements in TypeScript ?
Recent advancements in TypeScript include the addition of new features such as tuples, abstract classes, decorators, and template literal types. TypeScript is also continuously improving its type checking capabilities and compiler performance.
Explain the concept of inheritance in TypeScript ?
Inheritance in TypeScript is the ability of a class to inherit properties and methods from a parent class. Child classes can also override and extend the functionality of their parent class. TypeScript supports both single and multiple inheritance through the use of the “extends” keyword.
What are the different ways of declaring a Variable ?
The different ways of declaring a variable in TypeScript are:
Using the let keyword to declare a mutable variable.
Using the const keyword to declare an immutable variable.
Using the var keyword to declare a variable with function scope.
What are conditional types ? How do you create them ?
Conditional types are a feature in TypeScript that allow you to create a type that depends on a condition. You can create them using the extends keyword and a ternary operator, like this:
type TypeName<T> = T extends string ? "string" : T extends number ? "number" : T extends boolean ? "boolean" : T extends undefined ? "undefined" : T extends Function ? "function" : "object";
What are modules in TypeScript ?
Modules in TypeScript are used to organize code into reusable and maintainable units. A module is a file that can contain classes, interfaces, functions, and other code. You can export parts of a module using the export keyword, and import them in other modules using the import keyword.
What is the Function type in TypeScript ?
The Function type in TypeScript is used to describe the shape of a function. It includes the function’s parameters and return type, like this:
type MyFunction = (arg1: number, arg2: string) => boolean;
Does TypeScript support function overloading ?
Yes, TypeScript supports function overloading. This allows you to define multiple function signatures for the same function name, like this:
function myFunction(value: string): number; function myFunction(value: number): string; function myFunction(value: string | number): string | number { // implementation }
What are different components of TypeScript ?
Different components of TypeScript include the TypeScript compiler, the TypeScript language service, and the TypeScript language specification.
What is the difference between enum and const enums ?
The difference between enum and const enum is that enum generates a runtime object while const enum is resolved at compile-time and is removed from the generated JavaScript code. This makes const enum more efficient in terms of memory usage and runtime performance.
What is the difference between Private and Protected variables in TypeScript ?
The difference between private and protected variables in TypeScript is that private variables can only be accessed within the class that defines them, while protected variables can also be accessed within classes that inherit from the defining class.
What is the default access modifier for members of a class in TypeScript ?
The default access modifier for members of a class in TypeScript is public.
What is the unique symbol is used for ?
Unique symbols in TypeScript are used to create values that are guaranteed to be globally unique, which can be useful in certain situations where object identity needs to be established. They are created using the Symbol() function, which returns a unique symbol value that can be used as a property key in objects.
What is Mixin Class in TypeScript ?
Mixin Class in TypeScript: A mixin is a way to reuse a class’s code in multiple class hierarchies. It is a class that contains methods that can be added to other classes, allowing those classes to inherit the mixin’s behavior.
What is Structural Typing ?
Structural Typing: Structural typing is a type system in which types are based on their structure and not on their name or declaration. Two types are considered compatible if they have the same structure.
What is Typings in Typescript ?
Typings in TypeScript: Typings are a way of defining the types of external JavaScript libraries and modules in TypeScript. They allow developers to use external libraries in their TypeScript projects with type checking and code completion support.
Why do we need to use abstract keyword for classes and their methods in TypeScript ?
Abstract keyword in TypeScript: The abstract keyword is used to define abstract classes and methods in TypeScript. Abstract classes cannot be instantiated directly and must be subclassed. Abstract methods do not have an implementation in the abstract class and must be implemented in the subclass.
Does TypeScript supports function overloading ?
Function Overloading in TypeScript: Yes, TypeScript supports function overloading. This allows developers to define multiple function signatures for the same function, with different parameter types and return types. The appropriate signature is chosen at compile time based on the arguments passed to the function.
Explain how and why we could use property decorators in TS ?
Property decorators in TypeScript can be used to add functionality to properties of a class. They are functions that can be attached to a property declaration using the “@” symbol. They can be used to implement features such as validation, data binding, or logging.
How can you allow classes defined in a module to be accessible outside of the module ?
To allow classes defined in a module to be accessible outside of the module in TypeScript, you can use the “export” keyword before the class declaration. This will make the class public and allow it to be imported and used in other modules.
How to use external plain JavaScript libraries in TypeScript ?
To use external plain JavaScript libraries in TypeScript, you can install the library using a package manager such as NPM or Yarn, then include the library in your TypeScript project by importing it using the “import” keyword. You may also need to provide type definitions for the library if they are not included.
How TypeScript is optionally statically typed language ?
TypeScript is optionally statically typed, meaning that you can choose whether or not to specify types for your variables, functions, and other constructs. You can use type annotations to specify the types of your code elements, or you can rely on TypeScript’s type inference to automatically determine the types based on the code.
Explain the difference between declare enum vs declare const enum ?
The “declare enum” and “declare const enum” syntax in TypeScript are used to create enum types that can be used at runtime. The difference between them is that “declare enum” creates an enum with named keys and values, while “declare const enum” creates an enum with inline values that are replaced at compile time. “declare const enum” is more efficient, but can only be used in contexts where the values are known at compile time.
Explain what is Currying in TypeScript ?
Currying is a functional programming technique where a function with multiple arguments is transformed into a series of functions that each take a single argument. In TypeScript, currying can be achieved using arrow functions and function overloading.
Is it possible to generate TypeScript declaration files from JS library ?
Yes, it is possible to generate TypeScript declaration files from a JavaScript library using the “declare” keyword and specifying the types of the library’s functions and variables.
What are the differences between the private keyword and private fields in TypeScript ?
The “private” keyword in TypeScript is used to restrict access to a class member from outside the class, while “private” fields are a new feature in TypeScript 3.8 that allow for the definition of private class members using the “# ” syntax.
What are Ambients in TypeScripts and when to use them ?
Ambients in TypeScript are declarations that describe the shape of an external JavaScript library, allowing for type checking and IntelliSense in TypeScript code that uses that library. They are typically used when working with third-party JavaScript libraries that do not have TypeScript type definitions.
What is dynamic import expression ?
A dynamic import expression is a JavaScript feature that allows for the asynchronous loading of a module at runtime. In TypeScript, dynamic import expressions can be used to lazily load modules and improve performance. They are supported by TypeScript through the “import()” syntax.
What is the difference between unknown and any type ?
The main difference between unknown and any types in TypeScript is that unknown is a type-safe counterpart of any. Variables of type unknown can hold any value, just like variables of type any, but you cannot perform any operations on variables of type unknown without first narrowing the type to a more specific type.
What is the need of –incremental flag in TypeScript ?
The –incremental flag in TypeScript enables incremental compilation, which can significantly reduce compilation times in large projects by reusing the results of previous compilations.
What is Mixin Constructor Type ?
A Mixin Constructor Type is a type that describes a constructor function that can be used to mix in additional properties and methods to a class.
Why is the infer keyword needed in TypeScript ?
The infer keyword in TypeScript is used in conditional types to infer a type from another type. It allows you to extract a type from a more complex type, such as extracting the return type of a function or the type of an array element.
Why we need Index Signature in TypeScript ?
Index signatures allow us to define the type of values that can be accessed using a string or number as the key. This is useful when working with dynamic object properties or arrays, as it provides type safety when accessing these values.
What are the benefits of using TypeScript ?
TypeScript provides static type checking, which can catch errors at compile-time rather than runtime. This can lead to more robust code and improved developer productivity. Additionally, TypeScript provides better code organization and documentation through interfaces, enums, and type aliases.
How does TypeScript support optional type annotations ?
TypeScript supports optional type annotations through the use of the “?” character. This allows us to specify that a variable or parameter may be undefined, null, or have a certain type.
How does TypeScript support Interfaces ?
Interfaces in TypeScript are used to define the shape of objects or classes. They allow us to define the types of properties and methods that an object or class should have, which can help with type checking and code organization.
What is the difference between “declare” and “const” ?
declare” is used to declare types that are defined outside of TypeScript, such as those provided by libraries or the global scope. “const” is used to define a constant value, which cannot be changed once it has been assigned a value.
What is the difference between “let” and “var” ?
In TypeScript, “let” is used to declare a block-scoped variable while “var” is used to declare a variable with function scope.
Can you explain the concept of Generics in TypeScript ?
Generics in TypeScript allow for the creation of reusable code that can work with different types of data. They enable the creation of functions, classes, and interfaces that can be parameterized with different types of data.
What are the different ways to declare an array in TypeScript ?
There are two ways to declare an array in TypeScript: using the square bracket notation “[]” or using the generic array type “Array<T>”.
What is the difference between type and interface in TypeScript ?
In TypeScript, a type is a more specific definition of a data type, while an interface is a contract for an object to adhere to. A type can be used to describe the shape of an object, while an interface can define methods and properties that an object must implement.
Can you explain how to use Decorators in TypeScript ?
Decorators in TypeScript allow for the modification of classes, methods, and properties at runtime. They can be used to add behavior or metadata to a class or its members.
How does TypeScript handle inheritance ?
In TypeScript, inheritance is handled through the use of the “extends” keyword. A child class can inherit properties and methods from a parent class and can also override or extend those properties and methods. Additionally, TypeScript supports abstract classes and methods which can be used as templates for child classes to implement.
Can you give an example of how to use enums in TypeScript ?
Here’s an example of using enums in TypeScript:
enum Colors { Red, Green, Blue, } let selectedColor = Colors.Red;
How does TypeScript handle module loading ?
TypeScript uses module loaders such as CommonJS, AMD, ES6, and SystemJS to load modules. The module system is configurable via the module and moduleResolution options in the tsconfig.json file.
Can you explain the concept of namespaces in TypeScript ?
Namespaces in TypeScript are used to group related code into a single namespace, which can be used to avoid naming conflicts. Namespaces are declared using the namespace keyword, and can be nested. For example:
namespace MyNamespace { export class MyClass { } }
What is the purpose of the “as” keyword in TypeScript ?
The as keyword in TypeScript is used for type assertions, which allow you to tell the compiler that a value of one type is actually of another type. For example:
let myValue: any = "hello"; let myLength: number = (myValue as string).length;
What is the purpose of the “extends” keyword in TypeScript ?
The extends keyword in TypeScript is used to create a class that inherits properties and methods from another class. For example:
class Animal { move(distanceInMeters: number = 0) { console.log(`Animal moved ${distanceInMeters}m.`); } } class Dog extends Animal { bark() { console.log('Woof! Woof!'); } } let dog = new Dog(); dog.bark(); dog.move(10);
What is the purpose of the “implements” keyword in TypeScript ?
The “implements” keyword in TypeScript is used to declare that a class implements a particular interface, which means that the class must provide an implementation for all the methods and properties defined in the interface.
What is the difference between a static and instance member in TypeScript ?
In TypeScript, a static member is associated with the class itself, while an instance member is associated with each instance of the class. Static members can be accessed using the class name, while instance members can only be accessed through an instance of the class.
What is the difference between a class and an interface in TypeScript ?
In TypeScript, a class is a blueprint for creating objects with specific properties and methods, while an interface is a description of the shape of an object, defining the names and types of its properties and methods but not providing any implementation details.
Can you give an example of how to use a class in TypeScript ?
Here’s an example of a class in TypeScript:
class Car { make: string; model: string; year: number; constructor(make: string, model: string, year: number) { this.make = make; this.model = model; this.year = year; } getAge() { return new Date().getFullYear() - this.year; } } const myCar = new Car('Toyota', 'Corolla', 2010); console.log(myCar.getAge()); // Output: 13
Can you give an example of how to use a constructor in TypeScript ?
Here’s an example of a constructor in TypeScript:
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } const john = new Person('John', 30); console.log(john.name); // Output: "John" console.log(john.age); // Output: 30
What is the purpose of the “super” keyword in TypeScript ?
The “super” keyword in TypeScript is used to call a method or constructor of a parent class.
What is the difference between a “private” and a “public” member in TypeScript ?
A “private” member in TypeScript can only be accessed within the class where it was declared, while a “public” member can be accessed from anywhere.
Can you give an example of how to use a function in TypeScript ?
Here’s an example of how to use a function in TypeScript:
function addNumbers(num1: number, num2: number): number { return num1 + num2; } console.log(addNumbers(2, 3)); // Output: 5
Can you give an example of how to use the “this” keyword in TypeScript ?
Here’s an example of how to use the “this” keyword in TypeScript:
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } introduce(): void { console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`); } } const john = new Person('John', 30); john.introduce(); // Output: Hi, my name is John and I'm 30 years old.