TypeScript Interview Questions
TypeScript Interview Questions
© Copyright by Interviewbit
Contents
Conclusion
51. Conclusion
Why TypeScript?
As JavaScript projects grow in size, they become difficult to maintain. There are a few
reasons for this. First, JavaScript was never designed to build large-scale
applications. Its original purpose was to provide small scripting functionality for a
web page. Until recently, it didn’t provide tools and constructs for structuring large
projects, such as classes, modules, and interfaces. Also, TypeScript is dynamically
typed. It doesn’t support features such as IntelliSense.
TypeScript files use a .ts extension, in contrast to the .js extension used by the
JavaScript files. Since TypeScript is a superset of JavaScript, all valid JavaScript code
is a valid TypeScript code, and renaming a .js file to .ts won’t change anything. Here is
an example of a standard TypeScript program that adds two numbers and returns
the result. Notice how the arguments and the return types are annotated with their
type.
When you compile a TypeScript file using the tsc command, the Typescript compiler
generates vanilla JavaScript that gets executed. For example, this is what the
compiler will produce for the above snippet of code.
function add(a, b) {
const sum = a + b;
return sum;
}
TypeScript adds optional static typing and language features such as classes and
modules. It’s important to know that all these advanced features add zero cost to
JavaScript. A typeScript is purely a compile-time tool. Once you compile, you are le
with plain, idiomatic JavaScript. TypeScript is a language for application scale
JavaScript development.
You can also create an array using the short-hand syntax as follows:
console.log(employee.name);
console.log(employee.salary);
TypeScript assumes a variable is of type any when you don’t explicitly provide the
type, and the compiler cannot infer the type from the surrounding context.
If a variable is of type void, you can only assign the null or undefined values to that
variable.
You can narrow down a variable of an unknown type to something specific by doing
typeof checks or comparison checks or using type guards. For example, we can get
rid of the above error by
let: Declares a block-scoped local variable. Similar to var, you can optionally set the
value of a variable during the declaration. For example,
let a = 5;
if (true) {
let a = 10;
console.log(a); // 10
}
console.log(a); // 5
const a = 5;
if (true) {
a = 10; // Error: Cannot assign to 'a' because it is a constant.(2588)
}
In the example above, because the property ‘z’ is marked as optional, the compiler
won’t complain if we don’t provide it during the initialization.
foo = "Anders";
greet(foo); // "Good morning, ANDERS"
You might wonder why we need a ‘never’ type when we already have ‘void’. Though
both types look similar, they represent two very different concepts.
A function that doesn't return a value implicitly returns the value undefined in
JavaScript. Hence, even though we are saying it’s not returning anything, it’s
returning ‘undefined’. We usually ignore the return value in these cases. Such a
function is inferred to have a void return type in TypeScript.
In contrast, a function that has a never return type never returns. It doesn't return
undefined, either. There are 2 cases where functions should return never type:
1. In an unending loop e.g a while(true){} type loop.
2. A function that throws an error e.g function foo(){throw new Exception('Error
message')}
enum Team {
Alpha,
Beta,
Gamma,
Delta
}
let t: Team = Team.Delta;
By default, the enums start the numbering at 0. You can override the default
numbering by explicitly assigning the values to its members.
TypeScript also lets you create enums with string values as follows:
enum Author {
Anders = "Anders",
Hejlsberg = "Hejlsberg"
};
In TypeScript, you can use the typeof operator in a type context to refer to the type of
a property or a variable.
In contrast, the rest arguments allow a function caller to provide a variable number
of arguments from an array. Consider the following example.
first.push(...second);
console.log(first); // [1, 2, 3, 4, 5, 6]
multiply({ a: 1, b: 2, c: 3 });
You can simplify the above code by using an interface or a named type, as follows:
type ABC = { a: number; b: number; c: number };
multiply({ a: 1, b: 2, c: 3 });
class Employee {
name: string;
salary: number;
You can create an instance (or object) of a class by using the new keyword.
console.log(john.salary); // 60000
john.promote();
console.log(john.salary); // 70000
Using arrow functions syntax, the same function can be defined as:
You can further simplify the syntax by getting rid of the brackets and the return
statement. This is allowed when the function body consists of only one statement.
For example, if we remove the temporary sum variable, we can rewrite the above
function as:
console.log(`${greeting}, ${name}`);
}
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
‘forEach’ function
‘for..of’ statement
let x = foo?.bar.baz();
Function overloading allows us to define multiple functions with the same name, as
long as their number of parameters or the types of parameters are different.
The following example defines two overloads for the function buildDate. The first
overload takes a number as a parameter, whereas the second takes three numbers as
parameters. These are called overload signatures.
The body of the function also called an implementation signature, follows the
overload signatures. You can’t call this signature directly, as it’s not visible from the
outside. It should be compatible with the overload signatures.
const d1 = buildDate(87654321);
const d2 = buildDate(2, 2, 2);
function parse(s) {
console.log(s.split(' '));
}
parse("Hello world"); // ["Hello", "world"]
However, the code breaks down as soon as we pass a number or other type than a
string that doesn’t have a split() method on it. For example,
function parse(s) {
console.log(s.split(' ')); // [ERR]: s.split is not a function
}
parse(10);
noImplicitAny is a compiler option that you set in the tsconfig.json file. It forces the
TypeScript compiler to raise an error whenever it infers a variable is of any type. This
prevents us from accidentally causing similar errors.
28. What is an interface?
An interface defines a contract by specifying the type of data an object can have and
its operations. In TypeScript, you can specify an object’s shape by creating an
interface and using it as its type. It’s also called “duck typing”.
In TypeScript, you can create and use an interface as follows:
interface Employee {
name: string;
salary: number;
}
Interfaces are an effective way to specify contracts within your code as well as outside
your code.
greet(): void {
console.log("Hello, there. I am a writer.");
}
}
setTimeout(function () {
console.log('Run after 2 seconds')
}, 2000);
You can invoke an anonymous function as soon as it’s created. It’s called ‘immediately
(function() {
console.log('Invoked immediately after creation');
})();
However, if we try to set the value to a type not included in the union types, we get
the following error.
Union types allow you to create new types out of existing types. This removes a lot of
boilerplate code as you don’t have to create new classes and type hierarchies.
interface Employee {
work: () => string;
}
interface Manager {
manage: () => string;
}
Since TypeScript 3.0, a tuple can specify one or more optional types using the ? as
shown below.
<> syntax:
interface Coordinate {
readonly x: number;
readonly y: number;
}
When you mark a property as readonly, it can only be set when you initialize the
object. Once the object is created, you cannot change it.
let c: Coordinate = { x: 5, y: 15 };
c.x = 20; // Cannot assign to 'x' because it is a read-only property.(2540)
Triple-slash directives also order the output when using --out or --outFile. The output
files are produced to the output file location in the same order as the input files.
interface Runnable {
run(): void;
}
A class can implement more than one interface. In this case, the class has to specify
all the contracts of those interfaces.
// OK
foo = "bar";
String literal types on their own are not that useful. However, you can combine them
into unions. This allows you to specify all the string values that a variable can take, in
turn acting like enums. This can be useful for function parameters.
greet("John", "hello");
// Error: Argument of type '"Howdy?"' is not assignable to parameter of type '"hi" | "h
greet("Mary", "Howdy?");
Template literal types can also expand into multiple strings via unions. It helps us
create the set of every possible string literal that each union member can represent.
// type ItemTwo = "five item" | "six item" | "green item" | "yellow item"
type ItemOne = `${Quantity | Color} item`;
class Rectangle {
length: number;
breadth: number
area(): number {
return this.length * this.breadth;
}
}
volume() {
return "Square doesn't have a volume!"
}
}
console.log(sq.area()); // 100
console.log(sq.volume()); // "Square doesn't have a volume!"
In the above example, because the class Square extends functionality from
Rectangle, we can create an instance of square and call both the area() and volume()
methods.
Here, if type C extends B, the value of the above type is TypeX. Otherwise, it is TypeY.
Function is a global type in TypeScript. It has properties like bind, call, and apply,
along with the other properties present on all function values.
You can always call a value of the Function type, and it returns a value of ‘any’ type.
Conclusion
51. Conclusion
TypeScript has been increasing in popularity for the last few years, and many large
organizations and popular frameworks have adopted TypeScript to manage their
large JavaScript codebases. It’s a valuable skill to have as a developer.
In this article, we explored the questions that a developer might get asked in an
interview. We have provided simple code examples to cement the concepts further.
Finally, you can use the multiple-choice questions at the end of the article to test
your understanding of the various topics in TypeScript.
Reference:
TypeScript Documentation
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions