TypeScript Interview Questions and Answers
Practice TypeScript interview questions and answers organized by difficulty, with revealable explanations and related topics.
Entry questions
11 questions- Question 1Entry
What are Modules in Typescript?
- TypeScript
Reveal answerHide answer
Modules in Typescript helps in organizing the code. There are 2 types of Modules — Internal and External Internal Modules are now replaceable by using Typescript’s namespace. External Modules used to specify and load dependencies between multiple external js files. If there is only one js file used, then external modules are not relevant.
- Question 2Entry
What is the difference between .ts and .tsx extensions in TypeScript?
- TypeScript
Reveal answerHide answer
Use .ts for pure TypeScript files, Use .tsx for files which contain JSX .
- Question 3Entry
How to perform string interpolation in TypeScript?
- TypeScript
Reveal answerHide answer
You can use template iterals, Template literals are literals delimited with backticks (`) . For example:
let value = 100; console.log(`The size is ${value}`); - Question 4Entry
How to call base class constructor from child class in TypeScript?
- TypeScript
Reveal answerHide answer
We can call base class constructor using super() .
- Question 5Entry
Do we need to compile TypeScript files and why?
- TypeScript
Reveal answerHide answer
Yes we do. Typescript is just a language Extension browsers can't interpret it. Converting from TypeScript to JavaScript is called compiling. Compiling doesn't mean binary code is created in this case. For this kind of translation, also the term transpilation is used instead of compilation.
- Question 6Entry
What are the benefits of TypeScript?
- TypeScript
Reveal answerHide answer
TypeScript has following benefits. It helps in code structuring. Use class based object oriented programming. Impose coding guidelines. Offers type checking. Compile time error checking. Intellisense.
- Question 7Entry
What is TypeScript and why do we need it?
- TypeScript
Reveal answerHide answer
JavaScript is the only client side language universally supported by all browsers. But JavaScript is not the best designed language. It’s not a class-based object-oriented language, doesn’t support class based inheritance, unreliable dynamic typing and lacks in compile time error checking. And TypeScript addresses all these problems. In other words, TypeScript is an attempt to “fix” JavaScript problems. TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict superset of JavaScript, and adds optional static typing and class-based object-oriented programming to the language. TypeScript is quite easy to learn and use for developers familiar with C#, Java and all strong typed languages. At the end of day “TypeScript is a language that generates plain JavaScript files.” As stated on Typescript official website, “TypeScript lets you write JavaScript the way you really want to. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.” Where “typed” means that it considers the types of variables, parameters and functions.
- Question 8Entry
What is TypeScript and why would I use it in place of JavaScript?
- TypeScript
Reveal answerHide answer
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run. In details: TypeScript supports new ECMAScript standards and compiles them to (older) ECMAScript targets of your choosing. This means that you can use features of ES2015 and beyond, like modules, lambda functions, classes, the spread operator, destructuring, today. JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. TypeScript adds type support to JavaScript. The type system of TypeScript is relatively rich and includes: interfaces, enums, hybrid types, generics, union and intersection types, access modifiers and much more. TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information. With strict null checks enabled ( --strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. To use TypeScript you need a build process to compile to JavaScript code. The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. TypeScript is open source (Apache 2 licensed, see github) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project.
- Question 9Entry
Explain generics in TypeScript
- TypeScript
Reveal answerHide answer
Generics are able to create a component or function to work over a variety of types rather than a single one.
/** A class definition with a generic parameter */ class Queue<T> { private data = []; push = (item: T) => this.data.push(item); pop = (): T => this.data.shift(); } const queue = new Queue<number>(); queue.push(0); queue.push("1"); // ERROR : cannot push a string. Only numbers allowed - Question 10Entry
List the built-in types in Typescript
- TypeScript
Reveal answerHide answer
These are also called the primitive types in TypeScript: Number type: it is used to represent number type values and represents double precision floating point values.
var variable_name: number;String type: it represents a sequence of characters stored as Unicode UTF-16 code. It is the same as JavaScript primitive type.
var variable_name: string;Boolean type: in Typescript, it is used to represent a logical value. When we use the Boolean type, we get output only in true or false. It is also the same as JavaScript primitive type.
var variable_name: bool;Null type: it represents a null literal and it is not possible to directly reference the null type value itself.
var variable_name:number = null;Undefined type: it is the type of undefined literal. This type of built-in type is the sub-type of all the types.
var variable_name:number = undefined; - Question 11Entry
What is TypeScript and why one should use it?
- TypeScript
Reveal answerHide answer
TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing and class-based object-oriented programming to the language.
Junior questions
23 questions- Question 1Junior
How do we create an enum with string values?
- TypeScript
Reveal answerHide answer
String-based enums (TypeScript 2.4) allow us to assign string values to an enum member. Consider:
enum E { hello = "hello", world = "world" }; - Question 2Junior
What is the purpose of Nullish Coalescing operator?
- TypeScript
Reveal answerHide answer
The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.Its main purpose is to simplify assigning default values. The nullish coalescing operator tests for null and undefined only. For example:
// Nullish coalescing console.log(0 ?? 'error') // 0 console.log('' ?? 'error') // '' console.log(null ?? 'error') // 'error' - Question 3Junior
What is Optional Chaining in TypeScript?
- TypeScript
Reveal answerHide answer
An optional chain is an optional expression followed by one or more subsequent regualr property access, element access, or call argument lists:
a?.b.c; // property access chain a?.b[x]; // element access chain a?.b(); // call chain Which means:When a is either null or undefined , the rest of the chain is also not evaluated. However, if a is any other value, the expression is evaluated as normal. In this cases, if a.b were either null or undefined , the expression would still throw as the ?. token only guards the value of a .
- Question 4Junior
How can we use optional chaining in TypeScript?
- TypeScript
Reveal answerHide answer
We can use optional chaining like:
let x = foo?.bar.baz();This is equivalent to:
let x = (foo === null || foo === undefined) ? undefined : foo.bar.baz(); - Question 5Junior
How to make Arrays that can only be read, TypeScript?
- TypeScript
Reveal answerHide answer
Using ReadonlyArray type describes Arrays that can only be read from. Any variable with a reference to a ReadonlyArray can't add, remove, or replace any elements of the array. For example:
function foo(arr: ReadonlyArray<string>) { arr.slice(); // okay arr.push("hello!"); // error! } - Question 6Junior
Describe what are conditional types in TypeScript?
- TypeScript
Reveal answerHide answer
Condtitional types added the ability to express non-uniform type mappings, A conditional type selects one of two possible types based on a condition expressed as a type relationship test For example:
T extends U ? X : Y The type above means when T is assignable to U the type is X , otherwise the type is Y . Evaluation of a conditional type is deferred when evaluation of the condition depends on type variables in T or U , but is resolved to either X or Y when the condition depends on no type variables. An example:
type TypeName<T> = T extends string ? "string" : T extends number ? "number" : T extends boolean ? "boolean" : T extends undefined ? "undefined" : T extends Function ? "function" : "object"; type T0 = TypeName<string>; // "string" type T1 = TypeName<"a">; // "string" type T2 = TypeName<true>; // "boolean" type T3 = TypeName<() => void>; // "function" type T4 = TypeName<string[]>; // "object" - Question 7Junior
What does the pipe, | mean in TypeScript?
- TypeScript
Reveal answerHide answer
This is called union type in TypeScript. A union type describes a value that can be one of several types.
Pipe(|) is used toseparate each type. So, for example number | string | boolean is the type of a value that can be a number , a string , or a boolean . For example:
let something: number | string | boolean; something = 1; // ok something = '1' // ok something = true // ok something = {}; // Error: Type '{}' is not assignable to type 'string | number | boolean' - Question 8Junior
What is Interface in TypeScript?
- TypeScript
Reveal answerHide answer
One of TypeScript’s core principles is that type-checking focuses on the shape that values have. An interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. When you define your interface you’re saying that any object (not an instance of a class) given this contract must be an object containing interfaces properties.
- Question 9Junior
Does TypeScript support all object oriented principles?
- TypeScript
Reveal answerHide answer
The answer is YES. There are 4 main principles to Object Oriented Programming: Encapsulation, Inheritance, Abstraction, and Polymorphism. TypeScript can implement all four of them with its smaller and cleaner syntax.
- Question 10Junior
How to implement class constants in TypeScript?
- TypeScript
Reveal answerHide answer
In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword." TypeScript 2.0 has the readonly modifier:
class MyClass { readonly myReadonlyProperty = 1; myMethod() { console.log(this.myReadonlyProperty); } } new MyClass().myReadonlyProperty = 5; // error, readonly - Question 11Junior
What is getters/setters in TypeScript?
- TypeScript
Reveal answerHide answer
TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.
class foo { private _bar:boolean = false; get bar():boolean { return this._bar; } set bar(theBar:boolean) { this._bar = theBar; } } var myBar = myFoo.bar; // correct (get) myFoo.bar = true; // correct (set) - Question 12Junior
How could you check null and undefined in TypeScript?
- TypeScript
Reveal answerHide answer
Just use:
if (value) { }It will evaluate to true if value is not: null undefined NaN empty string '' 0 false TypesScript includes JavaScript rules.
- Question 12Junior
What is Decorators in TypeScript?
- TypeScript
Reveal answerHide answer
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators are functions that take their target as the argument. With decorators we can run arbitrary code around the target execution or even entirely replace the target with a new definition. There are 4 things we can decorate in ECMAScript2016 (and Typescript): constructors, methods, properties and parameters.
- Question 13Junior
Could we use TypeScript on backend and how?
- TypeScript
Reveal answerHide answer
Typescript doesn’t only work for browser or frontend code, you can also choose to write your backend applications. For example you could choose Node.js and have some additional type safety and the other abstraction that the language brings.
- Install the default Typescript compiler npm i -g typescript
- 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" } } 3. Compile ts files tsc 4. Run node build/index.js - Question 13Junior
When to use interfaces and when to use classes in TypeScript?
- TypeScript
Reveal answerHide answer
If you need/wish to create an instance of perhaps a custom object, whilst getting the benefits of type-checking things such as arguments, return types or generics - a class makes sense. If you’re not creating instances - we have interfaces at our disposal, and their benefit comes from not generating any source code, yet allowing us to somewhat “virtually” type-check our code.
- Question 14Junior
Which object oriented terms are supported by TypeScript?
- TypeScript
Reveal answerHide answer
TypeScript supports following object oriented terms: Modules Classes Interfaces Data Types Member functions
- Question 14Junior
What is the difference between Classes and Interfaces in Typescript?
- TypeScript
Reveal answerHide answer
We use classes as object factories. A class defines a blueprint of what an object should look like and act like and then implements that blueprint by initialising class properties and defining methods. Classes are present throughout all the phases of our code. Unlike classes, an interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once code is transpiled to its target language, it will be stripped from interfaces. A class may define a factory or a singleton by providing initialisation to its properties and implementation to its methods, an interface is simply a structural contract that defines what the properties of an object should have as a name and as a type.
- Question 15Junior
What is a TypeScript Map file?
- TypeScript
Reveal answerHide answer
.map files are source map files that let tools map between the emitted JavaScript code and the TypeScript source files that created it. Many debuggers (e.g. Visual Studio or Chrome's dev tools) can consume these files so you can debug the TypeScript file instead of the JavaScript file.
- Question 16Junior
What is the difference between types String and string in TypeScript?
- TypeScript
Reveal answerHide answer
String is the JavaScript String type, which you could use to create new strings. string is the TypeScript string type, which you can use to type variables, parameters and return values. For example:
var s1 = new String("Avoid newing things where possible"); var s2 = "A string, in TypeScript of type 'string'"; var s3: string = String("Hello World"); - Question 17Junior
What is Type Erasure in TypeScript?
- TypeScript
Reveal answerHide answer
TypeScript removes: type annotations, interfaces, type aliases, and other type system constructs during compilation. Consider TS input:
var x: SomeInterface;JS output:
var x; - Question 18Junior
What are the difference beetween Typescript and JavaScript?
- TypeScript
Reveal answerHide answer
It is an object oriented programming language (not pure). Here it is static typing (We can declare a variable in multiple ways). ex: var num : number. It has interfaces. It has optional parameter feature. It has Rest Parameter feature. Supports generics. Supports Modules Number, string etc. are the interfaces.
- Question 19Junior
What are assertion functions?
- TypeScript
Reveal answerHide answer
Assertion functions is a specific set of functions that throw an error if something unexpected happened. Consider:
assert (someValue === 42);If someValue isn't equal to 42 , then assert will throw an AssertionError .
- Question 20Junior
Which access modifiers are implied when not specified?
- TypeScript
Reveal answerHide answer
Everything in a class is public if not specified. Everything in a module is private unless the export keyword is used.
Mid questions
31 questions- Question 1Mid
What are different components of TypeScript?
- TypeScript
Reveal answerHide answer
There are mainly 3 components of TypeScript .
- Language – The most important part for developers is the new language. The language consist of new syntax, keywords and allows you to write TypeScript.
- 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.
- Language Service – TypeScript language service which powers the interactive TypeScript experience in Visual Studio, VS Code, Sublime, the TypeScript playground and other editor.
- Question 1Mid
How to make a readonly tuple type in TypeScript?
- TypeScript
Reveal answerHide answer
To make a readonly tuple type, we can use the keyword readonly before the tuple type declaration body in TypeScript. Consider:
// a readonly tuple type type ReadonlyTupleType = readonly [string, number];// assign the tuple type to an array const arr: ReadonlyTupleType = ["John Doe", 100];// add a 3rd element to the array // Error. // Index signature in type 'ReadonlyTupleType' only permits reading. arr[2] = 1000; - Question 1Mid
How TypeScript is optionally statically typed language?
- TypeScript
Reveal answerHide answer
TypeScript is referred as optionally statically typed, which means you can ask the compiler to ignore the type of a variable. Using any data type, we can assign any type of value to the variable. TypeScript will not give any error checking during compilation. Consider:
var unknownType: any = 4; unknownType = "Okay, I am a string"; unknownType = false; // A boolean. - Question 2Mid
What is the difference between type and interface in TypeScript?
- TypeScript
Reveal answerHide answer
interface is a contract that the following properties should be there in an object. interface is not class . It is used when language does not support Multiple Inheritance. So interface can be a common structure between different classes. Interfaces can be extended:
interface A { x: number; } interface B extends A { y: string; } Interfaces can also be augmented interface C { m: boolean; } // ... later ... interface C { n: number; }Type is like a variable declaration which holds the information of typeof other variable. type is like a superset of interfaces, classes, function signature, other types or even values (like type mood = 'Good' | 'Bad' ). At the end type describes the possible structure or value of a variable:
type NumOrStr = number | string; type NeatAndCool = Neat & Cool; type JustSomeOtherName = SomeType;So in general if you just have a plain object type, as shown in your question, an interface is usually a better approach. If you find yourself wanting to write something that can't be written as an interface, or want to just give something a different name, a type alias is better.
- Question 2Mid
Why do we need to use abstract keyword for classes and their methods in TypeScript?
- TypeScript
Reveal answerHide answer
An abstract class is allowed to have methods with no implementation, and cannot be constructed. For example:
abstract class Base { abstract getThing(): string; getOtherThing() { return "hello"; } } let x = new Base(); // Error, 'Base' is abstract //Error, must either be 'abstract' or implement concrete 'getThing' class Derived1 extends Base {} class Derived2 extends Base { getThing() { return "hello"; } foo() { super.getThing(); // Error: cannot invoke abstract members through 'super' } } var x = new Derived2(); // OK var y: Base = new Derived2(); // Also OK y.getThing(); // OK y.getOtherThing(); // OK - Question 2Mid
How to use external plain JavaScript libraries in TypeScript?
- TypeScript
Reveal answerHide answer
- Include the library source file before the compiled TypeScript file
- In your TypeScript file before using the library, add
declare var libGlobal: any;- Use any library function just like normal .
- Question 3Mid
How to add types to an interface from another interface orextend types in TypeScript?
- TypeScript
Reveal answerHide answer
To add types to an interface from another interface (aka extending the types) in TypeScript, you can use the extends keywords after the interface name followed by the name of the interface to get the types from. For example:
// a simple interface interface PersonalDetails { name: string; age: number; }// another simple interface // which extends the `PersonalDetails` intrface interface AllDetails extends PersonalDetails { salary: number; isAdmin: boolean; }// a simple object using // the extended `AllDetails` interface const johnDetails: AllDetails = { name: "John Doe", age: 25, salary: 30000, isAdmin: true, }; // valid and satisfies the interface. - Question 3Mid
What is Mixin Class in TypeScript?
- TypeScript
Reveal answerHide answer
A mixin class is a class that implements a distinct aspect of functionality. Other classes can then include the mixin and access its methods and properties. That way, mixins provide a form of code reuse that is based oncomposing behaviour. Consider a Timestamped mixin that tracks the creation date of an object in a timestamp property:
type Constructor<T = {}> = new (...args: any[]) => T; function Timestamped<TBase extends Constructor>(Base: TBase) { return class extends Base { timestamp = Date.now(); isActivated = false; activate() { // a mixin that implements methods this.isActivated = true; } deactivate() { this.isActivated = false; } }; }So we can use it as:
class User { name: string; constructor(name: string) { this.name = name; } }// Create a new class by mixing `Timestamped` into `User` const TimestampedUser = Timestamped(User);// Instantiate the new `TimestampedUser` class const user = new TimestampedUser("John Doe");// We can now access properties from both the `User` class // and our `Timestamped` mixin in a type-safe manner console.log(user.name); console.log(user.timestamp); // Now, `isActivated` is true user.activate(); console.log(user.isActivated); - Question 3Mid
What is Structural Typing?
- TypeScript
Reveal answerHide answer
The idea behind Structural Typing is that two types are compatible if their members are compatible. For example: In C# or Java, two classes named MyPoint and YourPoint , both with public int properties x and y , are not interchangeable, even though they are identical. But in a structural type system, the fact that these types have different names is immaterial. Because they have the same members with the same types, they are identical. Consider:
interface Pet { name: string; } class Dog { name: string; } let pet: Pet; // OK, because of structural typing pet = new Dog(); - Question 4Mid
How to check the type of a variable or constant in TypeScript?
- TypeScript
Reveal answerHide answer
To check the type of a variable or a constant, you can use the typeof operator followed by the variable name in TypeScript.
Consider:
// a simple variable let name = "John Doe";// check if the "name" variable type is of "string" if (typeof name === "string") { console.log("It is of 'string' type"); } else { console.log("It is not of 'string' type"); }/* OUTPUT: */ // It is of 'string' type - Question 4Mid
What are the use cases for a const assertion?
- TypeScript
Reveal answerHide answer
const assertions are used to tell the TypeScript compiler one of the following:
Object properties are Readonly const assertion Arrays become Readonly Tubles const assertion A variable value should be treated as Literal Type
const assertion const assertion - Question 5Mid
What are some use cases of template literal types in TypeScript?
- TypeScript
Reveal answerHide answer
Make a new type from the string literal type of TypeScript.
type Justin = 'justin'; type JustinLee = '${Justin} Lee';Combine string and type to make a new type.
type Banana = 'banana'; type Toppings = 'chocalate' | 'strawberries' | 'blueberries' | 'syrub';// type BananaToppings = 'banana chocolate' | 'banana strawberries' | 'banana blueberries' | 'banana syrup'; type BananaToppings = `${Banana} ${Toppings}`; Key Remapping in Mapped Types type Options = { [K in "isLoading" | "hasElements" | "isActive"]?: boolean; }; // same as // type Options = { // isLoading?: boolean, // hasElements?: boolean, // isActive?: boolean //}; - Question 5Mid
What is Mixin Class in TypeScript?
- TypeScript
Reveal answerHide answer
A mixin class is a class that implements a distinct aspect of functionality. Other classes can then include the mixin and access its methods and properties. That way, mixins provide a form of code reuse that is based oncomposing behaviour. Consider a Timestamped mixin that tracks the creation date of an object in a timestamp property:
type Constructor<T = {}> = new (...args: any[]) => T; function Timestamped<TBase extends Constructor>(Base: TBase) { return class extends Base { timestamp = Date.now(); isActivated = false; activate() { // a mixin that implements methods this.isActivated = true; } deactivate() { this.isActivated = false; } }; }So we can use it as:
class User { name: string; constructor(name: string) { this.name = name; } }// Create a new class by mixing `Timestamped` into `User` const TimestampedUser = Timestamped(User);// Instantiate the new `TimestampedUser` class const user = new TimestampedUser("John Doe");// We can now access properties from both the `User` class // and our `Timestamped` mixin in a type-safe manner console.log(user.name); console.log(user.timestamp); // Now, `isActivated` is true user.activate(); console.log(user.isActivated); - Question 6Mid
List a few rules of private fields in TypeScript
- TypeScript
Reveal answerHide answer
Private fields start with a # character. Sometimes we call these private names. Every private field name is uniquely scoped to its containing class. TypeScript accessibility modifiers like public or private can't be used on private fields. Private fields can't be accessed or even detected outside of the containing class - even by JS users! Sometimes we call this hard privacy. Consider:
class Person { #name: string; constructor(name: string) { this.#name = name; } greet() { console.log(`Hello, my name is ${this.#name}!`); } } let jeremy = new Person("Jeremy Bearimy"); jeremy.#name; // ~~~~~ // Property '#name' is not accessible outside class 'Person' // because it has a private identifier. - Question 7Mid
What does Short-Circuiting mean in TypeScript?
- TypeScript
Reveal answerHide answer
If the expression on the LHS of ?. evaluates to null or undefined , the RHS is not evaluated. This concept is called short-circuiting. For example:
a?.[++x] // `x` is incremented if and only if `a` is not null/undefined a == null ? undefined : a[++x] - Question 8Mid
What is the fundamental difference between Optional Chaining ( ?. ) and Non-null assertion operator ( ! ) in TypeScript?
- TypeScript
Reveal answerHide answer
Non-null assertion operator: Will not null guard your property chain. It just tells TypeScript that the value is never going to be null . But, if your value is indeed null , then your code will crash. Optional chaining: Will null check the property before it continues down the property chain, essentially guarding that value against being null or undefined .
If it finds that the property is null or undefined , then TypeScript will simply stop executing the property chain further and your code will proceed. Optional chaining ?. is safer to use than non-null assertions !.
- Question 9Mid
Is there a way to check for both null and undefined in TypeScript?
- TypeScript
Reveal answerHide answer
Using a juggling-check (it is where the type is juggled), you can test both null and undefined in one hit:
if (x == null) {If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:
if (x === null) { - Question 10Mid
How to make an array with a specific length or array elements in TypeScript?
- TypeScript
Reveal answerHide answer
To make an array with a specific length or array elements, we can use the concept of tuple types in TypeScript. A tuple type in TypeScript is basically an array but it knows beforehand how many array elements it will hold and what type it will hold at each index. To make a tuple type in TypeScript: We can use a type alias type declaration Then use the square brackets symbol( [] ) Inside the brackets we can write out the type we need to use at each index of the array For example:
// a simple tuple type when used on // an array should hold only 3 elements. // the 0th index should be `string` type // the 1st index should be `number` type // the 2nd index should be `number` type type MyTuple = [string, number, number];// using the `MyTuple` type an array // where it has 3 elements in the array // 0th index: has `string` type value // 1st index: has `number` type value // 2nd index: has `number` type value const myArr: MyTuple = ["John Doe", 100, 1000]; // valid. // Type '[string, number, number, number]' is not assignable to type 'MyTuple'. // Source has 4 element(s) but target allows only 3. const myArr2: MyTuple = MyTuple = ["John Doe", 100, 1000, 10000]; // Error. - Question 11Mid
Explain how and why we could use property decorators in TS?
- TypeScript
Reveal answerHide answer
Decorators can be used to modify the behavior of a class or become even more powerful when integrated into a framework. For instance, if your framework has methods with restricted access requirements (just for admin), it would be easy to write an @admin method decorator to deny access to non-administrative users, or an @owner decorator to only allow the owner of an object the ability to modify it.
class CRUD { get() { } post() { } @admin delete() { } @owner put() { } } - Question 12Mid
What is the unique symbol is used for?
- TypeScript
Reveal answerHide answer
As of TypeScript 2.7 there is a unique symbol type which is used to allow using symbols as unique literals. Each reference to a unique symbol implies a completely unique identity that’s tied to a given declaration. It is a way of declaring a literal akin to e.g. const x: 'test' . If you want to assign a different value than test to x you would get an error, also comparisons will be checked. Consider:
// Works declare const Foo: unique symbol;// Error! 'Bar' isn't a constant. let Bar: unique symbol = Symbol();// Works - refers to a unique symbol, but its identity is tied to 'Foo'. let Baz: typeof Foo = Foo;// Also works. class C { static readonly StaticSymbol: unique symbol = Symbol(); } - Question 13Mid
Why do we need to use abstract keyword for classes and their methods in TypeScript?
- TypeScript
Reveal answerHide answer
An abstract class is allowed to have methods with no implementation, and cannot be constructed. For example:
abstract class Base { abstract getThing(): string; getOtherThing() { return "hello"; } } let x = new Base(); // Error, 'Base' is abstract //Error, must either be 'abstract' or implement concrete 'getThing' class Derived1 extends Base {} class Derived2 extends Base { getThing() { return "hello"; } foo() { super.getThing(); // Error: cannot invoke abstract members through 'super' } } var x = new Derived2(); // OK var y: Base = new Derived2(); // Also OK y.getThing(); // OK y.getOtherThing(); // OK - Question 14Mid
What is the difference between enum and const enum s?
- TypeScript
Reveal answerHide answer
If an enum is const , all references to its members inlined, means that a reference to an enum member is replaced by its numeric equivalent when compiled. const enums do not produce a lookup table when compiled. If an enum declaration does not have the const modifier, references to its members are inlined only if the members are non-computed. A non-const, non-declared enum will produce a lookup table. Consider non const case:
enum Cheese { Brie, Cheddar }When compiled to JavaScript, this will emit a lookup table:
var Cheese; (function (Cheese) { Cheese[Cheese["Brie"] = 0] = "Brie"; Cheese[Cheese["Cheddar"] = 1] = "Cheddar"; })(Cheese || (Cheese = {})); const case: const enum Foo { A = 4 } var x = Foo.A; // emitted as "var x = 4;", always - Question 15Mid
What is the default access modifier for members of a class in TypeScript?
- TypeScript
Reveal answerHide answer
In TypeScript, each member of class is public by default.
- Question 15Mid
What is the difference between Private and Protected variables in TypeScript?
- TypeScript
Reveal answerHide answer
Private methods/members are accessible only from inside the class. Protected methods/members are accessible from inside the class and extending class as well. For example:
class A { private x: number; protected y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } getX(): number { return this.x; } getY(): number { return this.y; } } class B extends A { multiply(): number { return this.x * this.y; } } - Question 16Mid
What is Typings in Typescript?
- TypeScript
Reveal answerHide answer
TypeScript is mainly about adding types to JavaScript. When you use external libraries like jQuery or moment.js, there are no information of the types in that code. So in order to use it with TypeScript, you also have to get files that describe the types of that code. These are the type declaration files, most often with the file extension name .d.ts . Fortunately people have written those kinds of type declaration files for most common javascript libraries out there. Typings was just a tool to install those files. It is now best practice to just use npm .
- Question 16Mid
Does TypeScript supports function overloading?
- TypeScript
Reveal answerHide answer
Yes, TypeScript does support function overloading but the implementation is a bit different if we compare it to OO languages. We are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.
class Foo { myMethod(a: string); myMethod(a: number); myMethod(a: number, b: string); myMethod(a: any, b?: string) { alert(a.toString()); } } - Question 18Mid
Explain Project References and its benefits
- TypeScript
Reveal answerHide answer
Project references allow TypeScript projects to depend on other TypeScript projects Specifically, allows tsconfig.json files to reference other tsconfig.json files Its benefits: Greatly improve build times, Enforce logical separation between components,
Organize your code in new and better ways.
- Question 18Mid
How can you allow classes defined in a module to be accessible outside of the module?
- TypeScript
Reveal answerHide answer
Classes define in a module are available within the module. Outside the module you can’t access them.
module Vehicle { class Car { constructor ( public make: string, public model: string) { } } var audiCar = new Car("Audi", "Q7"); } // This won't work var fordCar = Vehicle.Car("Ford", "Figo");As per above code, fordCar variable will give us compile time error. To make classes accessible outside module use export keyword for classes.
module Vehicle { export class Car { constructor ( public make: string, public model: string) { } } var audiCar = new Car("Audi", "Q7"); } // This works now var fordCar = Vehicle.Car("Ford", "Figo"); - Question 19Mid
What are the use cases for a const assertion?
- TypeScript
Reveal answerHide answer
const assertions are used to tell the TypeScript compiler one of the following: Object properties are Readonly const assertion Arrays become Readonly Tubles const assertion A variable value should be treated as Literal Type
const assertion const assertion - Question 19Mid
What are different components of TypeScript?
- TypeScript
Reveal answerHide answer
There are mainly 3 components of TypeScript .
- Language – The most important part for developers is the new language. The language consist of new syntax, keywords and allows you to write TypeScript.
- 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.
- Language Service – TypeScript language service which powers the interactive TypeScript experience in Visual Studio, VS Code, Sublime, the TypeScript playground and other editor.
- Question 20Mid
How to choose between never , unknown , and any in TypeScript?
- TypeScript
Reveal answerHide answer
Use never in positions where there will not or should not be a value. Use unknown where there will be a value, but it might have any type. Avoid using any unless you really need an unsafe escape hatch.
Expert questions
11 questions- Question 2Expert
Explain when to use declare keyword in TypeScript
- TypeScript
Reveal answerHide answer
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.
- Question 3Expert
What are Ambients in TypeScripts and when to use them?
- TypeScript
Reveal answerHide answer
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" /> - Question 4Expert
Is it possible to generate TypeScript declaration files from JS library?
- TypeScript
Reveal answerHide answer
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: 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.
- Question 5Expert
Explain the difference between declare enum vs declare const enum
- TypeScript
Reveal answerHide answer
declare emits no code and expects you to have defined the actual code elsewhere. This emits no lookup table:
declare enum Wine { Red, Wine }Wine.Red emits Wine.Red in JavaScript, but there won't be any Wine lookup table to reference so it's an error unless you've defined it elsewhere. declare const emits no lookup table as well: declare const enum Fruit { Apple, Pear } But it does inline! Fruit.Apple emits 0. But again Fruit[0] will error out at runtime because it's not inlined and there's no lookup table.
- Question 6Expert
How the never datatype can be useful?
- TypeScript
Reveal answerHide answer
It might be helpful for instance while create more advanced types to point what they are not. For example, let's declare our own NonNullable type:
type NonNullable<T> = T extends null | undefined ? never : T;Here we are checking if T is null or undefined . If it is then we are pointing that it should never happen. Then while using this type:
let value: NonNullable<string>; value = "Test"; value = null; // error - Question 7Expert
What is the need of --incremental flag in TypeScript?
- TypeScript
Reveal answerHide answer
Because TypeScript files are compiled, there is an intermediate step between writing and running your code. One of our goals is to minimize build time given any change to your program. The --incremental flag tells TypeScript to save information about the project graph from the last compilation. The next time TypeScript is invoked with --incremental it will use that information to detect the least costly way to type-check and emit changes to your project. This can avoid a full type-check and re-emit which can be costly. For example:
// tsconfig.json { "compilerOptions": { "incremental": true, "outDir": "./lib" }, "include": ["./src"] } - Question 8Expert
Explain the difference between declare enum vs declare const enum
- TypeScript
Reveal answerHide answer
declare emits no code and expects you to have defined the actual code elsewhere. This emits no lookup table:
declare enum Wine { Red, Wine }Wine.Red emits Wine.Red in JavaScript, but there won't be any Wine lookup table to reference so it's an error unless you've defined it elsewhere. declare const emits no lookup table as well: declare const enum Fruit { Apple, Pear } But it does inline! Fruit.Apple emits 0. But again Fruit[0] will error out at runtime because it's not inlined and there's no lookup table.
- Question 8Expert
What are the differences between the private keyword and private fields in TypeScript?
- TypeScript
Reveal answerHide answer
The private keyword is a compile time annotation. The private keyword tells the compiler that a property should only be accessible inside that class The private keyword is also not enforced at runtime.
class PrivateKeywordClass { private value = 1; } const obj = new PrivateKeywordClass(); obj.value // compiler error: Property 'value' is private and only accessible within class 'PrivateKeywordClass'However compile time checking can be easily bypassed, by casting away the type information.
const obj = new PrivateKeywordClass(); (obj as any).value // no compile errorPrivate fields ensure that properties are kept private at runtime
class PrivateFieldClass { #value = 1; getValue() { return this.#value; } } const obj = new PrivateFieldClass();// You can't access '#value' outside of class like this obj.value === undefined // This is not the field you are looking for. obj.getValue() === 1 // But the class itself can access the private field! // Meanwhile, using private field outside a class is a runtime syntax error:obj.#value// While trying to access the private fields of another class is a runtime type error:
class Other { #value; getValue(obj) {return obj.#value
// TypeError: Read of private field #value from an object which did // not contain the field } } new Other().getValue(new PrivateKeywordClass()); - Question 9Expert
What is the benefit of import assertions features in TypeScript?
- TypeScript
Reveal answerHide answer
import assertion enables us to pass additional information inline, in the module import statement This is a syntax used by runtimes to make sure that an import has an expected format. Note: This feature works with both normal import and dynamic import For example:
// normal import import json from "./myModule.json" assert { type: "json" };// dynamic import import("myModule1.json", { assert: { type: "json" } }); - Question 10Expert
How to make a union type from a type alias or interface properties in TypeScript?
- TypeScript
Reveal answerHide answer
To make a union type from a type alias or interface properties: You can use the indexed access type syntax Then write the property name to make the union type separated by the union operator symbol (|) in TypeScript. For example:
// a simple interface interface Car { name: string; yearMade: number; }// make a union type from the `name` and // `yearMade` properties from the `Car` interface type NameOrYear = Car["name" | "yearMade"]; // NameOrYear -> string | number - Question 11Expert
What does the tsconfig option lib do?
- TypeScript
Reveal answerHide answer
With --lib you can specify a list of built-in API declaration groups that you can choose to include in your project. For instance, if you expect your runtime to have support for Map , Set , and Promise (e.g. most evergreen browsers today), just include: --lib es2015.collection, es2015.promise Similarly, you can exclude declartions you do not want to include in your project. For example, DOM, if you are working on a node project using --lib es5, es6
Senior questions
15 questions- Question 5Senior
How would you overload a class constructor in TypeScript?
- TypeScript
Reveal answerHide answer
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); - Question 6Senior
What is dynamic import expression?
- TypeScript
Reveal answerHide answer
Dynamic import expressions are a new feature and part of ECMAScript that allows users to asynchronously request a module at any arbitrary point in your program This means that you can conditionally and lazily import other modules and libraries Consider:
async function getZipFile(name: string, files: File[]): Promise<File> { const zipUtil = await import("./utils/create-zip-file"); const zipContents = await zipUtil.getContentAsBlob(files); return new File(zipContents, name); } - Question 6Senior
Explain why that code is marked as WRONG?
- TypeScript
Reveal answerHide answer
Problem
/* WRONG */ interface Fetcher { getObject(done: (data: any, elapsedTime?: number) => void): void; } ### Solution Don’t useoptional 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.
- Question 7Senior
How to define a TypeScript class which has an index signature?
- TypeScript
Reveal answerHide answer
To define a class with an index signature, just write the index signature in the class: For example:
interface IRawParams { [key: string]: any } class Foo implements IRawParams { [k: string]: any; } - Question 7Senior
How to exclude property from type in TypeScript?
- TypeScript
Reveal answerHide answer
Using Omit helper type we can create a new type with some properties dropped from the original. For example:
interface Test { a: string; b: number; c: boolean; }// Omit a single property: type OmitA = Omit<Test, "a">; // Equivalent to: {b: number, c: boolean} //Or, to omit multiple properties: type OmitAB = Omit<Test, "a"|"b">; //Equivalen to: {c: boolean} - Question 8Senior
Why we need Index Signature in TypeScript?
- TypeScript
Reveal answerHide answer
The idea of the index singatures is to type objects of unknown structure when you only know the key and value types. For example:
const salary1 = { baseSalary: 100_000, yearlyBonus: 20_000 }; const salary2 = { contractSalary: 110_000 }; function totlaSalary(salaryObject: {[key: string]: number}) { let total = 0; for (const name in salaryObject) { total += salaryObject[name]; } return total; } totalSalary(salary1); // => 120_000 totalSalary(salary2) // => 110_000 { [key:string]: number } is theindex signature, which tells TypeScript that salaryObject has to be an object with string type as key and number type as value.
- Question 9Senior
In a?.b.c , if a.b is null , then a.b.c will evaluate to undefined , right?
- TypeScript
Reveal answerHide answer
No. It will throw a TypeError when attempting to fetch the property "c" of a.b . The opportunity of short-circuiting happens only at one time, just after having evaluated the LHS of the optional chaining operator. If the result of that checks is negative, the evaluation proceeds normally. In other words, the ?. operator has an effect only at the very moment it is evaluated. It does not change the semantics of subsequent property accesses, method or function calls.
- Question 10Senior
How to exclude property from type in TypeScript?
- TypeScript
Reveal answerHide answer
Using Omit helper type we can create a new type with some properties dropped from the original. For example:
interface Test { a: string; b: number; c: boolean; }// Omit a single property: type OmitA = Omit<Test, "a">; // Equivalent to: {b: number, c: boolean} //Or, to omit multiple properties: type OmitAB = Omit<Test, "a"|"b">; //Equivalen to: {c: boolean} - Question 12Senior
What is the difference between unknown and any type?
- TypeScript
Reveal answerHide answer
unknown is the type-safe counterpart of any Anything is assignable to unknown But unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing Likewise no operations are permitted on an unknown without first asserting or narrowing to a more specific type. For example:
let vAny: any = 10; // We can assign anything to any let vUnknown: unknown = 10; // We can assign anything to unknown just like any let s1: string = vAny; // Any is assignable to anything let s2: string = vUnknown // Invalid; we can't assign vUnknown to any other type (without an explicit assertion) vAny.method(); // Ok; anything goes with any vUnknown.method(); // Not ok; we don't know anything about this variable - Question 13Senior
Why is the infer keyword needed in TypeScript?
- TypeScript
Reveal answerHide answer
With infer , the compiler ensures that you have declared all type variables explicitly, Without infer , the compiler wouldn't know, if you wanted to introduce an additional type variable that is to be inferred, or if type varaible is just an accidental typing error/typo, infer exists to remove this ambiguity. Note: infer is always used within the extends clause of a conditional type. For example:
// Here we declare a new type variable `R` in `MyType`, which gets inferred from `T`. type MyTpe<T> = T extends infer R ? R : never; type T1 = MyType<{b: string}> // T1 is {b: string;}Usage of undeclared type parameters now can result in a compile error
type MyType2<T> = T extends R2 ? R2 : never; // error, R2 undeclared - Question 14Senior
Explain what is Currying in TypeScript?
- TypeScript
Reveal answerHide answer
Currying is the process of transforming a function that takes multiple arguments into a series of functions that take one argument at a time. For example:
const simpleAdd = (x: number, y: number) => x + y const test00 = simpleAdd(4, 6) // 10 Curried version of simpleAdd const curriedAdd = (x: number) => (y: number) => x + y const test01 = curriedAdd(4)(2) // 6 const test02 = curriedAdd(15) // Function const test03 = test02(5) // 20 - Question 15Senior
Explain what is never datatype in TypeScript?
- TypeScript
Reveal answerHide answer
If you specify never as the return type, the return statement of the function must not be reachable. The function will always throw an error, or there's an infinite loop somewhere. For example:
function infiniteLoop(): never { while (true) { } return 'this will never execute'; } - Question 17Senior
What is Mixin Constructor Type?
- TypeScript
Reveal answerHide answer
A mixin constructor type refers to a type that has a single construct signature with a single rest argument of
type any[] and an object-like return type. For example, given an object-like type X , new (...args: any[]) => Xis a mixin constructor type with an instance type X . Consider:
class Point { constructor(public x: number, public y: number) {} } class Person { constructor(public name: string) {} } type Constructor<T> = new (...args: any[]) => T; function Tagged<T extends Constructor<{}>>(Base: T) { return class extends Base { _tag: string; constructor(...args: any[]) { super(...args); this._tag = ""; } }; } const TaggedPoint = Tagged(Point); let point = new TaggedPoint(10, 20); point._tag = "hello"; class Customer extends Tagged(Person) { accountBalance: number; } let customer = new Customer("Joe"); customer._tag = "test"; customer.accountBalance = 0; - Question 18Senior
How does override keyword works in TypeScript?
- TypeScript
Reveal answerHide answer
When a method on a child class is marked with override , TypeScript will always make sure that a method with the same name exists in a the base class. This will help cut down on typos, and can give you a heads up if you were not aware that a function was changed or removed in the parent class. For example:
abstract class Animal { public sleep() { // some default logic } public eat() { // some default logic } } class Unicorn extends Animal { public override sleep() { // some new logic }// Error! The method `eats` does not // exists in the parent class! public override eats() { // some new logic } } - Question 20Senior
How would you overload a class constructor in TypeScript?
- TypeScript
Reveal answerHide answer
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);