DEV Community

Uzeyr OZ
Uzeyr OZ

Posted on • Updated on

Top 10 TypeScript Interview Questions You Must Prepare in 2023

What is TypeScript and how is it different from JavaScript?

TypeScript is an open-source programming language that is a strict syntactical superset of JavaScript, meaning that all JavaScript code is valid TypeScript code. However, TypeScript adds additional features such as static typing and class-based object-oriented programming to JavaScript.

** How can you define and use interfaces in TypeScript?

**

Interfaces in TypeScript are used to define a contract for the shape of an object, including the properties and methods it should have. They can be defined using the "interface" keyword, and can be implemented by a class using the "implements" keyword.

interface Person {
  firstName: string;
  lastName: string;
  birthDate: Date;
  getFullName(): string;
  getAge(): number;
}

class Employee implements Person {
  firstName: string;
  lastName: string;
  birthDate: Date;

  constructor(firstName: string, lastName: string, birthDate: Date) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDate = birthDate;
  }

  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }

  getAge(): number {
    let today = new Date();
    let age = today.getFullYear() - this.birthDate.getFullYear();
    let month = today.getMonth() - this.birthDate.getMonth();
    if (month < 0 || (month === 0 && today.getDate() < this.birthDate.getDate())) {
        age--;
    }
    return age;
  }
}

let employee = new Employee("Uzeyr", "OZCAN", new Date("1989-01-12"));
console.log(employee.getFullName()); // "Uzeyr OZCAN"
console.log(employee.getAge()); // 35

Enter fullscreen mode Exit fullscreen mode

In this example, the "Person" interface has a property called "birthDate" of type Date. The "Employee" class implements the "Person" interface and has a constructor which accepts birth date. Then, the class has added a new method called getAge() which will calculate the age from the birthdate and return it.

** What are the benefits of using TypeScript over JavaScript?**

TypeScript offers several benefits over JavaScript, such as improved code readability and maintainability with the use of static typing, improved developer productivity with features like interfaces and decorators, and better support for large-scale projects with features like modules and namespaces.

**

How can you use decorators in TypeScript?
**
Decorators in TypeScript are a way to add additional behavior to a class, method, or property by applying a function to the targeted item. They can be defined using the "@" symbol, followed by the name of the decorator function.

function readonly(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.writable = false;
}

class Example {
    @readonly
    name: string = "Uzeyr OZCAN";
}

let example = new Example();
example.name = "Uzeyr OZCAN"; // throws an error, because the property is read-only
console.log(example.name); // "Uzeyr OZCAN"
Enter fullscreen mode Exit fullscreen mode

In this example, we have defined a decorator function called "readonly" that sets the "writable" property of a property descriptor to false, making the property read-only. We have applied the decorator to the "name" property of the "Example" class using the "@" symbol. When we try to change the value of the name property, it throws an error because it's readonly.

Decorators are a feature of TypeScript and can be useful for adding metadata or behavior to a class, method, or property. In this example, we use the decorator to make a property read-only, but decorators can be used for a wide variety of purposes such as logging, validation, etc. Decorators can be defined as a function and applied to a class, method or property with the "@" symbol.

**
What are the main features of TypeScript's type system?
**
TypeScript has a robust type system that includes features such as static typing, type inference, interfaces, classes, and generics. This allows for improved code readability, maintainability, and error-checking.
Static Typing:

let name: string = "Uzeyr OZCAN";
let age: number = 35;
let isStudent: boolean = false;
Enter fullscreen mode Exit fullscreen mode

Type Inference:

let name = "Uzeyr OZCAN"; // Type is inferred as string
let age = 35; // Type is inferred as number
let isStudent = false; // Type is inferred as boolean
Enter fullscreen mode Exit fullscreen mode

Interfaces:

Copy code
interface Person {
firstName: string;
lastName: string;
age: number;
}

let person: Person = {
firstName: "John",
lastName: "Doe",
age: 30
};
Classes:

class Student {
    fullName: string;
    constructor(public firstName: string, public middleInitial: string, public lastName: string) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}
let student = new Student("Jane", "M.", "Doe");
console.log(student.fullName); // "Jane M. Doe"
Enter fullscreen mode Exit fullscreen mode

Generics:

function identity<T>(arg: T): T {
    return arg;
}

let output = identity<string>("myString");  // type of output will be 'string'
console.log(output); // "myString"`
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate some of the main features of TypeScript's type system, including static typing, type inference, interfaces, classes and generics. Static typing allows developers to explicitly specify the data types of variables and function arguments, improving code readability and maintainability. Type inference automatically determines the data types of variables, reducing the amount of code required. Interfaces and classes allow for object-oriented programming and code reuse, while generics provide a way to write flexible and reusable code.

**
How does TypeScript handle transpilation and compilation?
**
TypeScript code is first transpiled, or converted, into JavaScript code using the TypeScript compiler. The generated JavaScript code can then be run in any JavaScript runtime environment.

//example.ts
let name: string = "John Doe";
let age: number = 30;
let isStudent: boolean = false;

console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Is Student: ${isStudent}`);
Enter fullscreen mode Exit fullscreen mode

you can use the TypeScript compiler to transpile the TypeScript code in the example.ts file into JavaScript code by running the following command in the command line:

tsc example.ts

Enter fullscreen mode Exit fullscreen mode

This will generate a file named example.js in the same directory, which contains the transpiled JavaScript code:

var name = "John Doe";
var age = 30;
var isStudent = false;
console.log("Name: " + name);
console.log("Age: " + age);
console.log("Is Student: " + isStudent);
Enter fullscreen mode Exit fullscreen mode

As you can see, the generated JavaScript code is very similar to the original TypeScript code, but with a few key differences. One of the main differences is that the type annotations have been removed. The TypeScript compiler also includes several other features such as error checking, source maps, and configuration options.

Alternatively, you can also use a build tool such as webpack to handle the transpilation and compilation of your TypeScript code, which also provides many other features such as module bundling, code minification, and live reloading.

**
How can you use classes and objects in TypeScript?
**
TypeScript supports the use of classes and objects, which can be defined using the "class" keyword. Classes can have properties and methods, and can be instantiated as objects using the "new" keyword.

**

How can you handle type checking and type inference in TypeScript?
**
TypeScript uses a combination of type checking and type inference to ensure that variables and function arguments have the correct types. The compiler will check for type errors and provide feedback during development, and will use type inference to automatically determine the types of variables if they are not explicitly defined.

Here is an example of a simple class in TypeScript:

class Point {
  x: number;
  y: number;

  constructor(x: number, y: number) {
      this.x = x;
      this.y = y;
  }

  add(point: Point) {
      return new Point(this.x + point.x, this.y + point.y);
  }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, Point is the class name. It has two member variables x and y, which are both numbers. It also has a constructor, which is a special method that gets called when an object is created from the class, and it takes two arguments x and y. The constructor assigns the received values to the corresponding properties x and y.

You can create an object from the class using the new keyword:

let p1 = new Point(0, 10);
let p2 = new Point(10, 20);
let p3 = p1.add(p2);
console.log(p3); // Point {x: 10, y: 30}


Enter fullscreen mode Exit fullscreen mode

In this example, p1 and p2 are objects created from the Point class, and the add method is called on p1 object with p2 object as an argument, which returns a new object with the properties x and y as the sum of the properties of the two input objects.

How can you use modules and namespaces in TypeScript?

TypeScript supports the use of modules, which are used to organize and reuse code, and namespaces, which are used to prevent naming collisions. Modules can be imported and exported using the "import" and "export" keywords, and namespaces can be defined using the "namespace" keyword.

** How can you set up and configure a TypeScript project?**

Setting up and configuring a TypeScript project typically involves installing the TypeScript compiler and configuring the project's tsconfig.json file, which contains settings such as the target ECMAScript version and the source file locations. It can be easily done via using package manager like npm or yarn.

🌎🙂😎 Let's Connect!
My Twitter: @muzeyrozcan
My Substack (here I will publish more in-depth articles)

Top comments (0)