Google News
logo
TypeScript Interview Questions
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 = "Chanti";
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 = "Chanti";
let bar: string = foo as string;
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
};
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.
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
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"
};
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 
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] 
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 });
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"]
}
TypeScript Generics is a tool that provides a way of creating reusable components. It is able to create components that can work with a variety of data types rather than a single data type. Also, it provides type safety without compromising the performance, or productivity. Generics allow us to create generic classes, generic functions, generic methods, and generic interfaces.
 
In generics, a type parameter is written between the open (<) and close (>) brackets which makes it strongly typed collections. It uses a special kind of type variable <T> that denotes types.
 
Example :
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("edureka");
let output2 = identity<number>( 117 );
console.log(output1);
console.log(output2);