DEV Community

Rutvik Makvana
Rutvik Makvana

Posted on

TypeScript Interview Questions

Question - What is TypeScript?

  • TypeScript is a superset of Javascript
  • Adds static types, allowing for improved code quality and error checking before runtime.
  • It supports features like interfaces, enums, generics, and more.
  • Provides better error checking, enhanced tools, and improved code readability.

Question - What is explicit and implicit type assignment?

  • Explicit means writing out the type. Like below -
let firstName: string = "Rutvik";
Enter fullscreen mode Exit fullscreen mode
  • Implicit means TypeScript will guess the type, based on the value. The below type will be considered a number
let age = 23;
Enter fullscreen mode Exit fullscreen mode

Question - Difference between any, unknown and never in TypeScript?

  • The type of any is used to assign any type of a variable.
  • It will not give error even if you reassign another type.
let x: any = 10;
x = 'hello'; // No TypeScript error
console.log(x.toUpperCase()); // No TypeScript error
Enter fullscreen mode Exit fullscreen mode
  • The type unknown is better than type any, because it requires us checking the type before performing operations on value.
let y: unknown = 10;
// Type assertion needed before using y as number
if (typeof y === 'number') {
    console.log(y.toFixed(2));
}
Enter fullscreen mode Exit fullscreen mode
  • The type never represents value that never occurs.
  • It is typically used for return statements of function that doesn’t returns properly.
function throwError(message: string): never {
    throw new Error(message);
}
Enter fullscreen mode Exit fullscreen mode

Question - How do you give the type of Arrays?

  • For typing array, we need to give the type as below. In this below example the array can contain type of string only.
const names: string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // no error
Enter fullscreen mode Exit fullscreen mode
  • We can also use a readonly keyword, which prevents the array been changed.
const names: readonly string[] = ["Rutvik", "Rohit", "Virat"];
names.push("Bumrah"); // Error: Property 'push' does not exist on type 'readonly string[]'.
Enter fullscreen mode Exit fullscreen mode

Question - What is Type Inference in array?

  • If we don’t give any type to an array, it will infer the type automatically.
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error
Enter fullscreen mode Exit fullscreen mode

Question - What are tuples?

  • It is a type array with pre-defined length and types.
  • It is very useful in giving types of mixed array with different types.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
Enter fullscreen mode Exit fullscreen mode

Question - What are readonly tuples?

  • If we don’t make a tuple readonly, we can add more items to the one defined and TypeScript will not throw any error.
let ourTuple: [number, boolean, string];

// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
//No safety in indexes from 3
ourTuple.push('This is wrong');
Enter fullscreen mode Exit fullscreen mode
  • Now, to fix it we use the keyword readonly before the type.
let ourTuple: readonly [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Coding Hero was here'];
// throws error as it is readonly
ourTuple.push('Coding Hero took a day off');
Enter fullscreen mode Exit fullscreen mode

Question - How to give the types for Objects?

  • We can give the type of object by creating another object like structure and specifying the keys and the type of the keys in the object.
interface CarTypes {
    brand: string,
    model: string,
    year: number
}


const car: CarTypes = {
  brand: "Tata",
  model: "Punch",
  year: 2020
};
Enter fullscreen mode Exit fullscreen mode

Question - How to have optional properties in Objects?

  • To give an optional property or key, we need to add the ? after thet key.
interface CarTypes {
    brand: string,
    model: string,
    year?: number
}

const car: CarTypes = {
  brand: "Tata",
  model: "Punch"
};
Enter fullscreen mode Exit fullscreen mode

Question - Explain enum in TypeScript?

  • An enum is a type of variables which are constants. You have to use the values within it only.
  • The values are numeric by default and starts with 0 and increments by 1.
  • They can be numeric or string-based
enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}
console.log(Direction.Up); // 1
console.log(Direction.Down); // 2
Enter fullscreen mode Exit fullscreen mode
enum Direction {
  Up = "Up",
  Down = "Down",
  Left = "Left",
  Right = "Right"
}
console.log(Direction.Up); // Up
console.log(Direction.Down); // Down
Enter fullscreen mode Exit fullscreen mode

Question - What are Type Aliases?

  • They allow to define type with a custom name and can be used for all primitive types like string and number and also complex type like objects and arrays.
type CarTypes = {
   brand: string,
   model: string,
   year: number
}

const car: CarTypes = {
  brand: "Tata",
  model: "Punch",
  year: 2020
};
Enter fullscreen mode Exit fullscreen mode

Question - What are interfaces?

  • Interfaces are like type but can be used only for objects.
interface Square {
   length: number
}

const square: Square {
  length: 20
}

Enter fullscreen mode Exit fullscreen mode

Question - How to extend interfaces?

  • Interfaces can be extended with the extend keyword.
interface Square {
   length: number
}

interface ColorSquare extends Square {
    color: string
}

const square: ColorSquare {
  length: 20,
  color: blue
}
Enter fullscreen mode Exit fullscreen mode

Question - What are Union and Intersection types?

Union :-

  • Union types are used when the property can be more then one value, like string or number.
  • For this reason they are also called OR and are used by using | symbol.
let id: string | number;
id = "ABC123";
id = 123;
// id = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
Enter fullscreen mode Exit fullscreen mode

Intersection :-

  • Intersesction types are used when combines multiple types into one.
  • For this reason they are also called AND and are used by using & symbol.
interface Person {
  name: string;
}

interface Employee {
  employeeId: number;
}

type Worker = Person & Employee;

const worker: Worker = {
  name: "Rutvik",
  employeeId: 12345,
}
Enter fullscreen mode Exit fullscreen mode

Question - What are functions in Typescript ?

How to give the return type in function?

  • We can give the return types of functions with : symbol after function name.
function getSum(): number {
    return 24;
}

function printMessage(): void {
    console.log("Good Morning");
}
Enter fullscreen mode Exit fullscreen mode

How to give type of parameters in function?

  • We can give the type of parameters by mentioning them after each parameter with : symbol.
function sum(a: number, b: number) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

How to give optional, default and rest parameters in function?

  • With default parameter, we can mark a parameter as optional. Like this, where c is optional and denoted by ?.
function substract(a: number, b: number, c?: number) {
  return a - b -(c || 0);
}
Enter fullscreen mode Exit fullscreen mode
  • The default values(an ES6 feature), goes after the type.
function multiply(a: number, b: number=10) {
  return a * b;
}
Enter fullscreen mode Exit fullscreen mode
  • The rest parameters(an ES6 feature), are given the type of array, because they convert passed items in array.
function add(a: number, b: number, ...rest: number[]) {
  return a + b + rest.reduce((acc, curr) => acc+ curr, 0);
}
Enter fullscreen mode Exit fullscreen mode

Question - What is casting in TypeScript?

  • Casting is the process of overriding a type of a variable.
  • Like in the below example, the type is unknown but is made string while using with the as keyword.
let y: unknown = 'Welcome';
console.log((y as string).length);
Enter fullscreen mode Exit fullscreen mode
  • We can also use <> in place of as. Both means the same.
let y: unknown = 'Welcome';
console.log((<string>y).length);
Enter fullscreen mode Exit fullscreen mode

Question - What are Generics in TypeScript ?

  • Generics in Typeascript allow you to create reusable components or dunctions that can work with multiple data types.
function logAndReturn(value : number | string) : number | string {
     return value;
}

const numberResult = logAndReturn(42);
const stringResult = logAndReturn("Hello");
const booleanResult = logAndReturn(true);

# Using Generics :-

function logAndReturn<T>(value : T) : T {
    return value;
}

Enter fullscreen mode Exit fullscreen mode

Question - Utility Types in Typescript?

  • TypeScript provides Utility Types to simplify common type transformations.
  • These types make it easier to manipulate and interact with object and interface types.
  • Here’s a breakdown of some commonly used utility types:

1. Partial

  • Makes all properties of type T optional.
  • Use case: When you want to create an object where only some properties are required.
interface User {
  id: number;
  name: string;
  email: string;
}

const partialUser: Partial<User> = {
  name: "Rutvik",
};
Enter fullscreen mode Exit fullscreen mode

2. Required

  • Makes all properties of type T required.
  • Use case: When you want to enforce that all properties must be present.
interface User {
  id?: number;
  name?: string;
}

const fullUser: Required<User> = {
  id: 1,
  name: "Rutvik",
};
Enter fullscreen mode Exit fullscreen mode

3. Readonly

  • Makes all properties of type T read-only.
  • Use case: To ensure that an object’s properties cannot be modified.
interface User {
  id: number;
  name: string;
}

const readonlyUser: Readonly<User> = {
  id: 1,
  name: "Rutvik",
};

// readonlyUser.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
Enter fullscreen mode Exit fullscreen mode

4. Pick

  • Creates a type by picking a set of properties K from type T.
  • Use case: When you need only specific properties from a type.
interface User {
  id: number;
  name: string;
  email: string;
}

type UserPreview = Pick<User, "id" | "name">;

const user: UserPreview = {
  id: 1,
  name: "Rutvik",
};
Enter fullscreen mode Exit fullscreen mode

5. Omit

  • Creates a type by omitting a set of properties K from type T.
  • Use case: When you want all properties except specific ones.
interface User {
  id: number;
  name: string;
  email: string;
}

type UserWithoutEmail = Omit<User, "email">;

const user: UserWithoutEmail = {
  id: 1,
  name: "Rutvik",
};
Enter fullscreen mode Exit fullscreen mode

6. Record

  • Constructs a type with keys K and values of type T.
  • Use case: To create an object type with fixed keys and consistent value types.
type Roles = "admin" | "user" | "guest";

const roleDescriptions: Record<Roles, string> = {
  admin: "Has full access",
  user: "Can view and edit own data",
  guest: "Can only view public data",
};
Enter fullscreen mode Exit fullscreen mode

7. Exclude

  • Excludes from type T all types that are assignable to U.
  • Use case: To filter out specific types.
type AllRoles = "admin" | "user" | "guest";
type NonAdminRoles = Exclude<AllRoles, "admin">; // "user" | "guest"
Enter fullscreen mode Exit fullscreen mode

8. Extract

  • Extracts from type T only types that are assignable to U.
  • Use case: To narrow down types to a specific subset.
type AllRoles = "admin" | "user" | "guest";
type AdminRole = Extract<AllRoles, "admin">; // "admin"
Enter fullscreen mode Exit fullscreen mode

9. NonNullable

  • Excludes null and undefined from type T.
  • Use case: To ensure a value is neither null nor undefined.
type UserName = string | null | undefined;
type ValidUserName = NonNullable<UserName>; // string
Enter fullscreen mode Exit fullscreen mode

10. ReturnType

  • Infers the return type of a function type.
  • Use case: To capture and use the return type of a function.
function getUser() {
  return { id: 1, name: "Rutvik" };
}

type UserType = ReturnType<typeof getUser>; // { id: number; name: string; }
Enter fullscreen mode Exit fullscreen mode

11. InstanceType

  • Constructs a type consisting of the instance type of a constructor function type T.
  • Use case: To get the type of a class instance.
class User {
  id = 1;
  name = "Rutvik";
}


type UserInstance = InstanceType<typeof User>; // User
Enter fullscreen mode Exit fullscreen mode

12. Parameters

  • Extracts the types of parameters of a function type.
  • Use case: To reuse the parameter types of a function.
function greet(name: string, age: number): void {}

type GreetParams = Parameters<typeof greet>; // [string, number]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)