Typescript Interview Questions

Typescript Interview Questions

1. What is TypeScript, and how does it differ from JavaScript?

Answer: TypeScript is a superset of JavaScript that adds static types. It allows for better tooling and error detection during development.

 

                

            let name: string = "Alice"; // Type annotation

            // name = 123; // Error: Type 'number' is not assignable to type 'string'

                

                

2. What are the benefits of using TypeScript?

Answer:

 

Static Typing: Helps catch errors at compile-time.

Enhanced IDE Support: Better autocompletion and navigation.

Interfaces: Helps define contracts within your code.

Type Inference: Automatically infers types based on values.

3. How do you define a variable in TypeScript?

Answer: You can define a variable using let, const, or var, followed by a type annotation.

 

                

            let age: number = 25;

            const isStudent: boolean = true;

                

                

4. What are interfaces in TypeScript?

Answer: Interfaces define the structure of an object, allowing you to enforce certain properties and types.

 

                

            interface Person {

              name: string;

              age: number;

            }

            

            const alice: Person = {

              name: "Alice",

              age: 30,

            };

                

                

5. What is a union type in TypeScript?

Answer: Union types allow a variable to hold values of different types, specified using the pipe (|) operator.

 

                

            let value: string | number;

            value = "Hello"; // Valid

            value = 42; // Valid

            // value = true; // Error: Type 'boolean' is not assignable to type 'string | number'

                

                

6. What is a tuple in TypeScript?

Answer: A tuple is an array with a fixed number of elements, where each element can be of a different type.

 

                

            let user: [string, number] = ["Alice", 25];

                

                

7. How do you define a function in TypeScript?

Answer: You can define a function with parameter types and a return type.

 

                

            function add(a: number, b: number): number {

              return a + b;

            }

                

                

8. What are generics in TypeScript?

Answer: Generics allow you to create reusable components that can work with any data type while maintaining type safety.

 

                

            function identity(arg: T): T {

              return arg;

            }

            

            let output = identity("Hello");

                

                

9. How do you handle optional properties in TypeScript?

Answer: Optional properties can be defined using a question mark (?) in the interface or type definition.

 

                

            interface Person {

              name: string;

              age?: number; // Optional property

            }

            

            const bob: Person = { name: "Bob" }; // Valid

                

                

10. What is the any type in TypeScript?

Answer: The any type allows you to opt-out of type checking, making it useful for dynamic content but reducing type safety.

 

                

            let data: any;

            data = 42; // Valid

            data = "Hello"; // Still valid

                

                

11. How do you use TypeScript with React?

Answer: You can use TypeScript in React by defining props and state types, typically using interfaces or type aliases.

 

                

            import React from 'react';

            

            interface Props {

              message: string;

            }

            

            const MyComponent: React.FC = ({ message }) => {

              return 

{message}

;

            };

                

                

12. What is type assertion in TypeScript?

Answer: Type assertion allows you to specify a type for a variable when you know more than TypeScript about its type.

 

                

            let someValue: any = "Hello";

            let strLength: number = (someValue as string).length;

                

                

13. What is an enum in TypeScript?

Answer: Enums are a way to define a set of named constants, which can be numeric or string values.

 

                

            enum Direction {

              Up = 1,

              Down,

              Left,

              Right,

            }

            

            let move: Direction = Direction.Up; // move = 1

                

                

14. What are type guards in TypeScript?

Answer: Type guards are expressions that check the type of a variable at runtime, helping TypeScript understand the variable's type.

 

                

            function isString(value: any): value is string {

              return typeof value === 'string';

            }

            

            let input: string | number = "Hello";

            

            if (isString(input)) {

              console.log(input.length); // TypeScript knows input is a string here

            }

                

                

15. How do you define a class in TypeScript?

Answer: You can define a class with properties, methods, and access modifiers like public, private, and protected.

 

                

            class Person {

              private name: string;

            

              constructor(name: string) {

                this.name = name;

              }

            

              public greet(): string {

                return `Hello, my name is ${this.name}`;

              }

            }

                

                

16. What are the access modifiers in TypeScript?

Answer:

 

public: Accessible everywhere.

private: Accessible only within the class.

protected: Accessible within the class and its subclasses.

17. What is the difference between interface and type?

Answer:

 

Interface: Extensible and can be merged with other interfaces.

Type: More flexible, can represent primitive types, union types, etc.

                

            interface A {

              propA: string;

            }

            

            type B = {

              propB: number;

            };

                

                

18. How do you create a union type with interfaces?

Answer: You can combine multiple interfaces using a union type.

 

                

            interface Cat {

              meow: () => void;

            }

            

            interface Dog {

              bark: () => void;

            }

            

            type Pet = Cat | Dog;

            

            const pet: Pet = {

              meow: () => console.log("Meow!"),

            };

                

                

19. What are mapped types in TypeScript?

Answer: Mapped types allow you to create new types by transforming properties of existing types.

 

                

            type Person = {

              name: string;

              age: number;

            };

            

            type ReadonlyPerson = {

              readonly [K in keyof Person]: Person[K];

            };

                

                

20. How do you handle exceptions in TypeScript?

Answer: You can handle exceptions using try-catch blocks, just like in JavaScript.

 

                

            try {

              throw new Error("An error occurred");

            } catch (e) {

              console.error(e.message);

            }

                

                

21. What is the purpose of the never type in TypeScript?

Answer: The never type represents values that never occur, such as functions that throw errors or infinite loops.

 

                

            function throwError(message: string): never {

              throw new Error(message);

            }

                

                

22. How do you work with asynchronous code in TypeScript?

Answer: You can use async and await along with type annotations for promise-based functions.

 

                

            async function fetchData(): Promise {

              return "Data fetched";

            }

                

                

23. What is a tuple in TypeScript?

Answer: A tuple is a fixed-length array with specific types defined for each position.

 

                

            let tuple: [string, number];

            tuple = ["Hello", 42];

                

                

24. What is the difference between null and undefined in TypeScript?

Answer: undefined means a variable has been declared but not assigned a value, whereas null is an intentional absence of any value.

 

25. How do you define a generic function in TypeScript?

Answer: You define a generic function by adding a type parameter in angle brackets <T>.

 

                

            function identity(value: T): T {

              return value;

            }

            

            const num = identity(42); // T is number

                

                

26. What is the purpose of the Partial utility type?

Answer: The Partial utility type makes all properties in a type optional.

 

                

            interface Person {

              name: string;

              age: number;

            }

            

            type PartialPerson = Partial;

            

            const p: PartialPerson = { name: "John" };

                

                

27. What is the purpose of the Readonly utility type?

Answer: The Readonly utility type makes all properties in a type immutable.

 

                

            interface Person {

              name: string;

              age: number;

            }

            

            type ImmutablePerson = Readonly;

            

            const p: ImmutablePerson = { name: "Alice", age: 30 };

            // p.name = "Bob"; // Error: cannot assign to 'name'

                

                

28. How do you ensure a function never returns in TypeScript?

Answer: Use the never type for functions that throw errors or have infinite loops.

 

                

            function fail(message: string): never {

              throw new Error(message);

            }

                

                

29. What is the keyof operator in TypeScript?

Answer: The keyof operator creates a union type of all property keys of a given type.

 

                

            interface Person {

              name: string;

              age: number;

            }

            

            type PersonKeys = keyof Person; // 'name' | 'age'

                

                

30. What are conditional types in TypeScript?

Answer: Conditional types use the format T extends U ? X : Y to return different types based on a condition.

 

                

            type IsString = T extends string ? true : false;

            

            type Test1 = IsString; // true

            type Test2 = IsString; // false

                

                

31. What is the difference between unknown and any in TypeScript?

Answer: unknown is safer than any as it requires a type check before usage.

 

                

            let value: unknown = "Hello";

            // console.log(value.toUpperCase()); // Error

            if (typeof value === "string") {

              console.log(value.toUpperCase()); // Works

            }

                

                

32. What is the infer keyword in TypeScript?

Answer: The infer keyword is used in conditional types to infer a type from a generic.

 

                

            type ReturnType = T extends (...args: any[]) => infer R ? R : never;

            

            function add(a: number, b: number): number {

              return a + b;

            }

            

            type Result = ReturnType; // number

                

                

33. How do you create a record type in TypeScript?

Answer: Use the Record utility type to create an object type with specific keys and values.

 

                

            type Role = "admin" | "user";

            type UserRoles = Record;

            

            const roles: UserRoles = {

              admin: "Admin User",

              user: "Standard User",

            };

                

                

34. How do you define a type alias in TypeScript?

Answer: A type alias is defined using the type keyword followed by the alias name and its definition.

 

                

            type Point = { x: number, y: number };

            

            const point: Point = { x: 10, y: 20 };

                

                

35. What are the advantages of using TypeScript over JavaScript?

Answer: TypeScript provides static typing, better tooling support, early error detection, and more maintainable code through its strict type system.

 

36. What is the void type in TypeScript?

Answer: The void type represents the absence of any type, often used in functions that do not return a value.

 

                

            function logMessage(message: string): void {

              console.log(message);

            }

                

                

37. How do you define a class in TypeScript?

Answer: A class in TypeScript is defined using the class keyword, and you can use TypeScript-specific features like access modifiers and type annotations.

 

                

            class Person {

              constructor(public name: string, public age: number) {}

            }

            

            const person = new Person("John", 30);

                

                

38. How do you create an interface in TypeScript?

Answer: An interface in TypeScript is defined using the interface keyword, and it can describe object structures, function signatures, and more.

 

                

            interface Person {

              name: string;

              age: number;

            }

            

            const person: Person = { name: "Alice", age: 25 };

                

                

39. How do you use the super keyword in TypeScript?

Answer: The super keyword is used to call the constructor or methods of a parent class.

 

                

            class Animal {

              constructor(public name: string) {}

              speak() {

                console.log(this.name + " makes a sound");

              }

            }

            

            class Dog extends Animal {

              constructor(name: string) {

                super(name); // Calling parent class constructor

              }

            }

            

            const dog = new Dog("Rex");

            dog.speak(); // Rex makes a sound

                

                

40. How does TypeScript handle inheritance?

Answer: TypeScript supports inheritance using the extends keyword, allowing classes to inherit properties and methods from a parent class.

 

41. What are access modifiers in TypeScript?

Answer: TypeScript supports three access modifiers: public (default), private, and protected, which control the visibility of class members.

 

                

            class Car {

              public model: string;

              private engine: string;

              protected color: string;

            

              constructor(model: string, engine: string, color: string) {

                this.model = model;

                this.engine = engine;

                this.color = color;

              }

            }

                

                

42. How do you handle asynchronous programming in TypeScript?

Answer: TypeScript handles asynchronous programming using async and await keywords for promises.

 

                

            async function fetchData(): Promise {

              return "Data loaded";

            }

            

            const data = await fetchData();

            console.log(data); // Data loaded

                

                

43. What is a module in TypeScript?

Answer: A module in TypeScript is a file that contains code and is considered a separate unit of functionality. You can export and import code between modules.

 

44. What are the differences between import and require in TypeScript?

Answer: import is statically analyzed and supports tree-shaking, while require is used in CommonJS and works dynamically.

 

45. What is the difference between let, const, and var in TypeScript?

Answer: let and const are block-scoped, while var is function-scoped. const also makes the variable immutable.

 

46. How do you declare and use a function in TypeScript?

Answer: Functions in TypeScript are declared similarly to JavaScript but with optional type annotations for parameters and return types.

 

                

            function add(x: number, y: number): number {

              return x + y;

            }

                

                

47. What is a namespace in TypeScript?

Answer: A namespace is a way to group related code in a modular structure. It helps avoid name conflicts and allows code organization.

 

48. How do you use export and import in TypeScript?

Answer: export is used to make code accessible outside the file, while import is used to bring in exported code from other modules.

 

                

            // file1.ts

            export const myVariable = "Hello";

            

            // file2.ts

            import { myVariable } from './file1';

            console.log(myVariable); // Hello

                

                

49. What is the as keyword used for in TypeScript?

Answer: The as keyword is used for type assertions, telling TypeScript to treat a value as a specific type.

 

                

            let value: any = "Hello";

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

                

                

50. How do you use never as a return type?

Answer: The never type is used for functions that never return a value, such as those that throw exceptions or run indefinitely.

 

                

            function error(message: string): never {

              throw new Error(message);

            }

                

                

© 2024 Interviews Prep. All rights reserved.

Share: