Typescript Interview Questions Flashcards
What are the primitive types in TypeScript?
TypeScript has three primitive types that are frequently used: string, number, and boolean. These correspond to the similarly named types in JavaScript.
string: represents text values such as “javascript”, “typescript”, etc.
number: represents numeric values like 1, 2, 32, 43, etc.
boolean: represents a variable that can have either a ‘true’ or ‘false’ value.
Explain how the arrays work in TypeScript.
We use arrays to store values of the same type. Arrays are ordered and indexed collections of values. The indexing starts at 0, i.e., the first element has index 0, the second has index 1, and so on.
Here is the syntax to declare and initialize an array in TypeScript.
let values: number[] = [];
values[0] = 10;
values[1] = 20;
values[2] = 30;
You can also create an array using the short-hand syntax as follows:
let values: number[] = [15, 20, 25, 30];
TypeScript provides an alternate syntax to specify the Array type.
let values: Array<number> = [15, 20, 25, 30];</number>
What is any type, and when to use it?
There are times when you want to store a value in a variable but don’t know the type of that variable in advance. For example, the value is coming from an API call or the user input. The ‘any’ type allows you to assign a value of any type to the variable of type any.
let person: any = “Foo”;
Here is an example that demonstrates the usage of any type.
// json may come from a third-party API
const employeeData: string = {"name": "John Doe", "salary": 60000}
;
// parse JSON to build employee object
const employee: any = JSON.parse(employeeData);
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.
What is void, and when to use the void type?
The void indicates the absence of type on a variable. It acts as the opposite type to any. It is especially useful in functions that don’t return a value.
function notify(): void {
alert(“The user has been notified.”);
}
If a variable is of type void, you can only assign the null or undefined values to that variable.
What is an unknown type, and when to use it in TypeScript?
The unknown type is the type-safe counterpart of any type. You can assign anything to the unknown, but the unknown isn’t assignable to anything but itself and any, without performing a type assertion of a control-flow-based narrowing. You cannot perform any operations on a variable of an unknown type without first asserting or narrowing it to a more specific type.
Consider the following example. We create the foo variable of unknown type and assign a string value to it. If we try to assign that unknown variable to a string variable bar, the compiler gives an error.
let foo: unknown = “Akshay”;
let bar: string = foo; // Type ‘unknown’ is not assignable to type ‘string’.(2322)
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 foo: unknown = “Akshay”;
let bar: string = foo as string;
What are the different keywords to declare variables in TypeScript?
var: Declares a function-scoped or global variable. You can optionally set its value during the declaration. Its behavior and scoping rules are similar to the var keyword in JavaScript. For example,
var foo = “bar”;
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: Declares a block-scoped constant value that cannot be changed after it’s initialized. For example,
const a = 5;
if (true) {
a = 10; // Error: Cannot assign to ‘a’ because it is a constant.(2588)
}
Provide the syntax of a function with the type annotations.
Functions are blocks of code to perform a specific code. Functions can optionally take one or more arguments, process them, and optionally return a value.
Here’s the TypeScript syntax to create and call a function.
function greet(name: string): string {
return Hello, ${name}
;
}
let greeting = greet(“Anders”);
console.log(greeting); // “Hello, Anders”
How to create objects in TypeScript?
Objects are dictionary-like collections of keys and values. The keys have to be unique. They are similar to arrays and are also sometimes called associative arrays. However, an array uses numbers to index the values, whereas an object allows you to use any other type as the key.
In TypeScript, an Object type refers to any value with properties. It can be defined by simply listing the properties and their types. For example,
let pt: { x: number; y: number } = {
x: 10,
y: 20
};
How to specify optional properties in TypeScript?
An object type can have zero or more optional properties by adding a ‘?’ after the property name.
let pt: { x: number; y: number; z?: number } = {
x: 10,
y: 20
};
console.log(pt);
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.
Explain the concept of null and its use in TypeScript.
In programming, a null value indicates an absence of value. A null variable doesn’t point to any object. Hence you cannot access any properties on the variable or call a method on it.
In TypeScript, the null value is indicated by the ‘null’ keyword. You can check if a value is null as follows:
function greet(name: string | null) {
if (name === null) {
console.log(“Name is not provided”);
} else {
console.log(“Good morning, “ + name.toUpperCase());
}
}
var foo = null;
greet(foo); // “Name is not provided”
foo = “Anders”;
greet(foo); // “Good morning, ANDERS”
What is undefined in TypeScript?
When a variable is declared without initialization, it’s assigned the undefined value. It’s not very useful on its own. A variable is undefined if it’s declared, but no value has been assigned to it. In contrast, null is assigned to a variable, and it represents no value.
console.log(null == null); // true
console.log(undefined == undefined); // true
console.log(null == undefined); // true, with type-conversion
console.log(null === undefined); // false, without type-conversion
console.log(0 == undefined); // false
console.log(‘’ == undefined); // false
console.log(false == undefined); // false
Explain the purpose of the never type in TypeScript.
As the name suggests, the never type represents the type of values that never occur. For example, a function that never returns a value or that always throws an exception can mark its return type as never.
function error(message: string): never {
throw new Error(message);
}
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.
// This function returns undefined
function greet(name: string) {
console.log(Hello, ${name}
);
}
let greeting = greet(“David”);
console.log(greeting); // undefined
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:
In an unending loop e.g a while(true){} type loop.
A function that throws an error e.g function foo(){throw new Exception(‘Error message’)}
Explain how enums work in TypeScript?
Enums allow us to create named constants. It is a simple way to give more friendly names to numeric constant values. An enum is defined by the keyword enum, followed by its name and the members.
Consider the following example that defines an enum Team with four values in it.
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”
};
What is the typeof operator? How is it used in TypeScript?
Similar to JavaScript, the typeof operator in TypeScript returns the type of the operand as a string.
console.log(typeof 10); // “number”
console.log(typeof ‘foo’); // “string”
console.log(typeof false); // “boolean”
console.log(typeof bar); // “undefined”
In TypeScript, you can use the typeof operator in a type context to refer to the type of a property or a variable.
let greeting = “hello”;
let typeOfGreeting: typeof greeting; // similar to let typeOfGreeting: string
What are the rest parameters and arguments in TypeScript?
A rest parameter allows a function to accept an indefinite number of arguments as an array. It is denoted by the ‘…’ syntax and indicates that the function can accept one or more arguments.
function add(…values: number[]) {
let sum = 0;
values.forEach(val => sum += val);
return sum;
}
const sum = add(5, 10, 15, 20);
console.log(sum); // 50
In contrast, the rest arguments allow a function caller to provide a variable number of arguments from an array. Consider the following example.
const first = [1, 2, 3];
const second = [4, 5, 6];
first.push(…second);
console.log(first); // [1, 2, 3, 4, 5, 6]
What is parameter destructuring?
Parameter destructing allows a function to unpack the object provided as an argument into one or more local variables.
function multiply({ a, b, c }: { a: number; b: number; c: number }) {
console.log(a * b * c);
}
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 };
function multiply({ a, b, c }: ABC) {
console.log(a * b * c);
}
multiply({ a: 1, b: 2, c: 3 });
Explain the TypeScript class syntax.
TypeScript fully supports classes. The TypeScript syntax for class declaration is similar to that of JavaScript, with the added type support for the member declarations.
Here is a simple class that defines an Employee type.
class Employee {
name: string;
salary: number;
constructor(name: string, salary: number) {
this.name = name;
this.salary = salary;
}
promote() : void {
this.salary += 10000;
}
}
You can create an instance (or object) of a class by using the new keyword.
// Create a new employee
let john = new Employee(“John”, 60000);
console.log(john.salary); // 60000
john.promote();
console.log(john.salary); // 70000
Explain the arrow function syntax in TypeScript.
Arrow functions provide a short and convenient syntax to declare functions. They are also called lambdas in other programming languages.
Consider a regular function that adds two numbers and returns a number.
function add(x: number, y: number): number {
let sum = x + y;
return sum;
}
Using arrow functions syntax, the same function can be defined as:
let add = (x: number, y: number): number => {
let sum = x + y;
return sum;
}
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:
let add = (x: number, y: number): number => x + y;
Arrow functions are often used to create anonymous callback functions in TypeScript. Consider the example below that loops over and filters an array of numbers and returns an array containing multiples of five. The filter function takes an arrow function.
let numbers = [3, 5, 9, 15, 34, 35];
let fiveMultiples = numbers.filter(num => (num % 5) == 0);
console.log(fiveMultiples); // [5, 15, 35]
Provide the syntax for optional parameters in TypeScript.
A function can mark one or more of its parameters as optional by suffixing its name with ‘?’. In the example below, the parameter greeting is marked optional.
function greet(name: string, greeting?: string) {
if (!greeting)
greeting = “Hello”;
console.log(${greeting}, ${name}
);
}
greet(“John”, “Hi”); // Hi, John
greet(“Mary”, “Hola”); // Hola, Mary
greet(“Jane”); // Hello, Jane
What is the purpose of the tsconfig.json file?
A tsconfig.json file in a directory marks that directory as the root of a TypeScript project. It provides the compiler options to compile the project.
Here is a sample tsconfig.json file:
{
“compilerOptions”: {
“module”: “system”,
“noImplicitAny”: true,
“removeComments”: true,
“outFile”: “../../built/local/tsc.js”,
“sourceMap”: true
},
“include”: [“src//”],
“exclude”: [“node_modules”, “**/.spec.ts”]
}