Monday, 4 September 2023

Git Interview Questions

 

1.What is Git and why is it used?

·         Git is the most popular, open-source, widely used, and an example of distributed version control system (DVCS) used for handling the development of small and large projects in a more efficient and neat manner.

2. What does the command git config do?

The git config command is a convenient way to set configuration options for defining the behavior of the repository, user information and preferences, git installation-based configurations, and many such things. 

For example:
To set up your name and email address before using git commands, we can run the below commands:

·         git config –global user.name “<<your_name>>”
 

·         git config --global user.email “<<your_email>>”

3. Can you explain head in terms of git and also tell the number of heads that can be present in a repository?

·         head is nothing but a reference to the last commit object of a branch.

·         For every repository, there will always be a default head referred to as “master” or now “main” (as per GitHub) but there is no restriction to the count of heads available. In other words, it can have any number of heads.

·         Usages:

- To go or checkout to 1 commit before the latest commit, we use 

·         git checkout HEAD~1

- To uncommit the last 3 commits without losing the changes, we first run 

·           git reset HEAD~3.

·         Then we can see the changes made in the last 3 commits and then update it manually and commit it finally.

- In order to uncommit the last 3 commits and also remove the changes, we can run the command: 
git reset --hard HEAD~3. This command will completely remove all the changes.

- To look into the changes made in the last 3 commits, we can run 

·         git diff HEAD~3

- To make a new commit by reverting the last 3 commits, we can run the command: 

·         git revert --no-commit HEAD~3...HEAD

4. What does git status command do?

git status command is used for showing the difference between the working directory and the index which is helpful for understanding git in-depth and also keep track of the tracked and non-tracked changes.

 

5.Define “Index”.

Before making commits to the changes done, the developer is given provision to format and review the files and make innovations to them. All these are done in the common area which is known as ‘Index’ or ‘Staging Area’.


In the above image, the “staged” status indicates the staging area and provides an opportunity for the people to evaluate changes before committing them.

6. Tell me something about git stash?

Git stash can be used in cases where we need to switch in between branches and at the same time not wanting to lose edits in the current branch. Running the git stash command basically

 pushes the current working directory state and index to the stack for future use and thereby providing a clean working directory for other tasks

git stash apply

 

7. What is the command used to delete a branch?

·         To delete a branch we can simply use the command git branch –d [head].

·         To delete a branch locally, we can simply run the command: git branch -d <local_branch_name>

·         To delete a branch remotely, run the command: git push origin --delete <remote_branch_name>

·         Deleting a branching scenario occurs for multiple reasons. One such reason is to get rid of the feature branches once it has been merged into the development branch

 

8. What differentiates between the commands git remote and git clone?

git remote command creates an entry in  git config that specifies a name for a particular URL. Whereas git clone creates a new git repository by copying an existing one located at the URL.

 

9. Differentiate between git pull and git fetch.

    

git pull 

git fetch

This command pulls new changes from the currently working branch located in the remote central repository.

This command is also used for a similar purpose but it follows a two step process: 
1. Pulls all commits and changes from desired branch and stores them in a new branch of the local repository. 
current
2. For changes to be reflected in the current / target branch, git fetch should be followed by git merge command.

git pull = git fetch + git merge 

 

10. Can you give differences between “pull request” and “branch”?

  

pull request

branch

This process is done when there is a need to put a developer’s change into another person’s code branch. 

A branch is nothing but a separate version of the code.

 

11. What is the difference between git stash apply vs git stash pop command?

·         git stash pop command throws away the specified stash (topmost stash by default) after applying it.

·         git stash apply command leaves the stash in the stash list for future reuse. In case we wanted to remove it from the list, we can use the git stash drop command.

git stash pop = git stash apply + git stash drop

 

12. What command helps us know the list of branches merged to master?

·         git branch --merged helps to get the list of the branches that have been merged into the current branch.

·         Note: git branch --no-merged lists the branches that have not been merged to the current branch

13. How will you resolve conflict in Git?

·         Conflicts occur whenever there are multiple people working on the same file across multiple branches. In such cases, git won't be able to resolve it automatically as it is not capable of deciding what changes has to get the precedence.

·         Following are the steps are done in order to resolve git conflicts:
1. Identify the files that have conflicts.
2. Discuss with members who have worked on the file and ensure that the required changes are done in the file.
3. Add these files to the staged section by using the git add command.
4. Commit these changes using the git commit command.
5. Finally, push the changes to the branch using the git.

 

14. What is best advisable step in cases of broken commit: Create an additional commit OR amend an existing commit?

·         It is always advisable to create an additional commit rather than amending the existing commit due to the following reasons:
- Doing the amend operation destroys the previously saved state of that commit. If only the commit message gets changes or destroyed, it's acceptable but there might be cases when the contents of the commits get amended. This results in the loss of important information associated with the commit.
- Over usage of 
git commit --amend can have severe repercussions as the small commit amend can continue to grow and gather unrelated changes over time.

 

15. How to revert a bad commit which is already pushed?

There can be cases where we want to revert from the pushed changes and go back to the previous version. To handle this, there are two possible approaches based on the situations:

·         Approach 1: Fix the bad changes of the files and create a new commit and push to the remote repository. This step is the simplest and most recommended approach to fix bad changes. You can use the command: git commit -m "<message>"

·         Approach 2: New commit can be created that reverts changes done in the bad commit. It can be done using git revert <name of bad commit>

git push origin <branch-name>


16.Explain steps involved in removing a file from git index without removing from the local file system?

·         git reset command for removing the file from the staged version and then adding that file to the .gitignore file to avoid repeating the same mistake again.

git reset <file_name> # remove file from index

17. Can you tell the differences between git revert and git reset?

git revert 

git reset

This command is used for creating a new commit that undoes the changes of the previous commit.

This command is used for undoing the local changes done in the git repository

Using this command adds a new history to the project without modifying the existing history

This command operates on the commit history, git index, and the working directory.

18. What is the meaning of “Index” or “Staging Area” in GIT?

When we are making the commits, we can make changes to it, format it and review it in the intermediate area known as ‘Staging Area’ or ‘Index’.







 


Type Script Interview Questions

 

1. 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

 


 

2. What is TypeScript ?

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.

 

 Typescript compiler generates vanilla JavaScript that gets executed.

3. Explain how the arrays work in TypeScript

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];

4. 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";

5. 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.

6. 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"; 

// Type 'unknown' is not assignable to type 'string'.(2322)

 let foo: unknown = "Akshay";

let bar: string = foo as string;

7.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)

}

8. 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"

9. 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.

10. Explain the purpose of the never type in TypeScript.

In TypeScript, the never type represents a type that indicates a value that will never occur. It's used to indicate scenarios where a function will never return or where a value cannot have any possible value, effectively representing the absence of a value.



11. What is enum in Typescript ?

an enum (short for "enumeration") is a way to define a set of named constant values.

enum Team {

      Alpha,

      Beta,

      Gamma,

      Delta

}

let t: Team = Team.Delta;

 

12 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 

13. 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 

14. Explain the TypeScript class syntax.

   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

15. Explain the arrow function syntax in TypeScript.

   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;

}

 

16. Provide the syntax for optional parameters in TypeScript.

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

 

17. 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"]
}

 

18. Explain the different variants of the for loop in TypeScript.

TypeScript provides the following three ways to loop over collections.

·         ‘for’ loop



·          

·         ‘forEach’ function

·         


·          

·         ‘for..of’ statement



 

19. Explain the symbol type in TypeScript.

  Symbols were introduced in ES6 and are supported by TypeScript. Similar to numbers and strings, symbols are primitive types. You can use Symbols to create unique properties for objects.

You can create symbol values by calling the Symbol() constructor, optionally providing a string key.

let foo = Symbol();

let bar = Symbol("bar"); // optional string key

A key characteristic of symbols is that they are unique and immutable.

let foo = Symbol("foo");

let newFoo = Symbol("foo");

 

let areEqual = foo === newFoo;

console.log(areEqual);  // false, symbols are unique 

20. Explain how optional chaining works in TypeScript.

Using optional chaining, the following expression

let x = foo === null || foo === undefined ? undefined : foo.bar.baz();

can be expressed as:

let x = foo?.bar.baz();

 

21. What is meant by type inference?

TypeScript can infer the type of a variable when you don’t provide an explicit type. This is known as type inference. This is usually done when the variables or parameters are initialized during the declaration.

For example, TypeScript knows that the variable foo is a string, even though we don’t mention string as a type.

let foo = "this is a string";

console.log(typeof foo);  // "string"


22. 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;

}

 function process(employee: Employee) {

        console.log(`${employee.name}'s salary = ${employee.salary}`);

}

 let john: Employee = {

        name: "John Doe",

        salary: 150000

}

 process(john);  // "John Doe's salary = 150000"

23. Does TypeScript support static classes? If not, why?

TypeScript doesn’t support static classes, unlike the popular object-oriented programming languages like C# and Java.

These languages need static classes because all code, i.e., data and functions, need to be inside a class and cannot exist independently. Static classes provide a way to allow these functions without associating them with any objects.

In TypeScript, you can create any data and functions as simple objects without creating a containing class. Hence TypeScript doesn’t need static classes. A singleton class is just a simple object in TypeScript

24. What are anonymous functions? Provide their syntax in TypeScript.

An anonymous function is a function without a name. Anonymous functions are typically used as callback functions, i.e., they are passed around to other functions, only to be invoked by the other function at a later point in time.

For example,

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 invoked function execution (IIFE)’,

For example:

(function() {

               console.log('Invoked immediately after creation');

})();

 

25. What are union types in TypeScript?

A union type is a special construct in TypeScript that indicates that a value can be one of several types. A vertical bar (|) separates these types.

 let value: string | number = "Foo";

value = 10;  // Okay

However, if we try to set the value to a type not included in the union types, we get the following error. 

value = true;  // Type 'boolean' is not assignable to type 'string | number'.(2322)

 

26. What are intersection types?

Intersection types let you combine the members of two or more types by using the ‘&’ operator. This allows you to combine existing types to get a single type with all the features you need.

The following example creates a new type Supervisor that has the members of types Employee and Manager.

interface Employee {

                    work: () => string;

}

interface Manager {

    manage: () => string;

}

 type Supervisor = Employee & Manager;

 // john can both work and manage

let john: Supervisor; 

27. What are type aliases? How do you create one?

Type aliases give a new, meaningful name for a type. They don’t create new types but create new names that refer to that type.

For example, you can alias a union type to avoid typing all the types everywhere that value is being used.

type alphanumeric = string | number;

let value: alphanumeric = "";

value = 10;


28. Explain the tuple types in TypeScript.

Tuples are a special type in TypeScript. They are similar to arrays with a fixed number of elements with a known type. However, the types need not be the same.

// Declare a tuple type and initialize it

let values: [string, number] = ["Foo", 15];

 // Type 'boolean' is not assignable to type 'string'.(2322)

// Type 'string' is not assignable to type 'number'.(2322)

let wrongValues: [string, number] = [true, "hello"]; // Error

Since TypeScript 3.0, a tuple can specify one or more optional types using the ? as shown below.

let values: [string, number, boolean?] = ["Foo", 15]  


29. Explain how tuple destructuring works in TypeScript.

 You can destructure tuple elements by using the assignment operator (=). The destructuring variables get the types of the corresponding tuple elements.  

let employeeRecord: [string, number] = ["John Doe", 50000];

let [emp_name, emp_salary] = employeeRecord;

console.log(`Name: ${emp_name}`);  // "Name: John Doe"

console.log(`Salary: ${emp_salary}`);  // "Salary: 50000"

After destructuring, you can’t assign a value of a different type to the destructured variable. For example,

emp_name = true;  // Type 'boolean' is not assignable to type 'string'.(2322)


30. What are type assertions in TypeScript?

Sometimes, you as a programmer might know more about the type of a variable than TypeScript can infer. Usually, this happens when you know the type of an object is more specific than its current type. In such cases, you can tell the TypeScript compiler not to infer the type of the variable by using type assertions.

TypeScript provides two forms to assert the types.

·         as syntax:

let value: unknown = "Foo";

let len: number = (value as string).length;

·         <> syntax:

let value: unknown = "Foo";

let len: number = (<string>value).length;

 

31. How to make object properties immutable in TypeScript? (hint: readonly)

You can mark object properties as immutable by using the readonly keyword before the property name. For example:

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)


32. What are triple-slash directives?

Triple-slash directives are single-line comments that contain a single XML tag. TypeScript uses this XML tag as a compiler directive.

You can only place a triple-slash directive at the top of the containing file. Only single or multi-line comments can come before a triple-slash directive. TypeScript treats them as regular comments if it occurs in the middle of a code block, after a statement.

The primary use of triple-slash directives is to include other files in the compilation process. For example, the following directive instructs the compiler to include a file specified by the path in the containing TypeScript file.

/// <reference path="..." />

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

 

33. Explain the purpose of the ‘in’ operator.

 The in operator is used to find if a property is in the specified object. It returns true if the property belongs to the object. Otherwise, it returns false.

const car = { make: 'Hyundai', model: 'Elantra', year: 2017 };

console.log('model' in car);  // true

console.log('test' in car);  // false