governor sindh it coursegovernor sindh it course typescript exam

Are you ready to challenge your Typescript skills and earn an e-certificate? Join Mehak Alamgir’s exclusive Zoom Class Typescript Quiz and stand out as a Typescript pro!

governor sindh it course typescript quiz preparation (Subjective Questions)

Question 1:

Write a TypeScript function that uses async/await to wait for 2 seconds and then returns a string “Hello World”.

function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function greet(): Promise<string> {
  await delay(2000);
  return "Hello World";
}

Question 2:

Create a TypeScript function that takes a callback function as an argument and uses setTimeout to call the callback after 1 second.

function delayedCallback(callback: () => void): void {
  setTimeout(callback, 1000);
}

Question 3:

Write a TypeScript function that returns a Promise that resolves with the value “Resolved!” after 3 seconds.

function resolveAfter3Seconds(): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Resolved!");
    }, 3000);
  });
}

Question 4:

Create a TypeScript function that uses async/await to wait for two Promises to resolve and then returns their results as an array.

async function waitForTwoPromises<T, U>(promise1: Promise<T>, promise2: Promise<U>): Promise<[T, U]> {
  const result1 = await promise1;
  const result2 = await promise2;
  return [result1, result2];
}

Question 5:

Write a TypeScript function that uses async/await to wait for a Promise to resolve and then logs the result to the console.

async function logResolvedPromise<T>(promise: Promise<T>): Promise<void> {
  const result = await promise;
  console.log(result);
}

Question 6:

Write a TypeScript function that uses async/await to wait for a Promise to reject and then logs the error to the console.

async function logRejectedPromise<T>(promise: Promise<T>): Promise<void> {
  try {
    await promise;
  } catch (error) {
    console.error(error);
  }
}

Question 7:

Create a TypeScript function that takes a number as an argument and returns a Promise that resolves with the square of the number after a delay of 1 second.

function squareAfterDelay(num: number): Promise<number> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(num * num);
    }, 1000);
  });
}

Question 8:

Write a TypeScript function that uses async/await to wait for an array of Promises to resolve and then returns an array of their results

async function waitForAllPromises<T>(promises: Promise<T>[]): Promise<T[]> {
  return await Promise.all(promises);
}
waitForAllPromises function: Uses Promise.all to wait for an array of promises to resolve and returns their results in an array.

Question 9:

Create a TypeScript function that uses setTimeout to call a function repeatedly every 2 seconds.

function callRepeatedly(func: () => void): void {
  setInterval(func, 2000);
}

Question 10:

Write a TypeScript function that uses async/await to wait for a Promise to resolve and then returns a new Promise that resolves with the result multiplied by 2.

async function doubleResolvedValue(promise: Promise<number>): Promise<number> {
  const result = await promise;
  return result * 2;
}

Reverse String in TypeScript

To reverse a string in TypeScript, you can split the string into an array of characters, reverse the array, and then join the characters back into a string. Here is an example:

function reverseString(str: string): string {
  return str.split('').reverse().join('');
}

// Example usage:
const originalString = "Hello, World!";
const reversedString = reverseString(originalString);
console.log(reversedString); // Output: "!dlroW ,olleH"

Function to Take a Shape and Call Its Draw Method

In TypeScript, you can define an interface for shapes that have a draw method, and then write a function that takes any shape implementing this interface and calls its draw method.

First, define the interface for the shape:

interface Shape {
  draw(): void;
}

class Circle implements Shape {
  draw(): void {
    console.log("Drawing a Circle");
  }
}

class Square implements Shape {
  draw(): void {
    console.log("Drawing a Square");
  }
}

function drawShape(shape: Shape): void {
  shape.draw();
}

// Example usage:
const circle = new Circle();
const square = new Square();

drawShape(circle); // Output: Drawing a Circle
drawShape(square); // Output: Drawing a Square

Base Class Animal with Subclasses Bird and Fish

Here is an example of a base class Animal with two subclasses, Bird and Fish:

class Animal {
  constructor(public name: string) {}

  move(): void {
    console.log(`${this.name} is moving.`);
  }
}

class Bird extends Animal {
  fly(): void {
    console.log(`${this.name} is flying.`);
  }
}

class Fish extends Animal {
  swim(): void {
    console.log(`${this.name} is swimming.`);
  }
}

// Example usage:
const bird = new Bird("Parrot");
bird.move(); // Output: Parrot is moving.
bird.fly();  // Output: Parrot is flying.

const fish = new Fish("Goldfish");
fish.move(); // Output: Goldfish is moving.
fish.swim(); // Output: Goldfish is swimming.

interface Shape {
  draw(): void;
}

class Circle implements Shape {
  draw(): void {
    console.log("Drawing a Circle");
  }
}

class Rectangle implements Shape {
  draw(): void {
    console.log("Drawing a Rectangle");
  }
}

// Example usage:
const circle = new Circle();
const rectangle = new Rectangle();

circle.draw(); // Output: Drawing a Circle
rectangle.draw(); // Output: Drawing a Rectangle

Interface Showing Public, Private, and Protected Data Modifiers

In TypeScript, interfaces cannot directly enforce access modifiers (public, private, protected), but you can illustrate the concept using a class that implements the interface.

interface User {
  getUsername(): string;
  getEmail(): string;
}

class UserDetails implements User {
  public username: string;
  private password: string;
  protected email: string;

  constructor(username: string, password: string, email: string) {
    this.username = username;
    this.password = password;
    this.email = email;
  }

  getUsername(): string {
    return this.username;
  }

  getEmail(): string {
    return this.email;
  }

  private getPassword(): string {
    return this.password;
  }
}

// Example usage:
const user = new UserDetails("johnDoe", "secret", "john@example.com");

console.log(user.getUsername()); // Output: johnDoe
console.log(user.getEmail());    // Output: john@example.com
// console.log(user.password);   // Error: Property 'password' is private and only accessible within class 'UserDetails'.
// console.log(user.email);      // Error: Property 'email' is protected and only accessible within class 'UserDetails' and its subclasses.

In this example:

  • The UserDetails class implements the User interface and includes public, private, and protected properties.
  • The public property username and methods getUsername and getEmail are accessible from outside the class.
  • The private property password and method getPassword are only accessible within the UserDetails class.
  • The protected property email is accessible within the UserDetails class and any subclasses but not from outside.

What is the difference between async and await keywords in TypeScript?

The async keyword is used to declare an asynchronous function that returns a Promise. The await keyword is used inside an async function to pause execution until the Promise resolves or rejects.

What is the purpose of the Promise.all method?

Promise.all takes an array of Promises and returns a single Promise that resolves when all the input Promises have resolved, or rejects if any of the input Promises reject.

Write a TypeScript function that fetches data from two APIs concurrently using Promise.all and returns the results as an array.

async function fetchDataFromApis(api1: string, api2: string): Promise<[any, any]> {
  const [result1, result2] = await Promise.all([
    fetch(api1).then(res => res.json()),
    fetch(api2).then(res => res.json())
  ]);
  return [result1, result2];
}

Create a TypeScript function that uses async/await to fetch user data from an API and log the user’s name. Handle any potential errors.

async function fetchUserData(api: string): Promise<void> {
  try {
    const response = await fetch(api);
    const user = await response.json();
    console.log(user.name);
  } catch (error) {
    console.error('Error fetching user data:', error);
  }
}

Write a TypeScript function that simulates an asynchronous operation (e.g., fetching data) and returns a Promise that resolves with a string after a delay of 2 seconds.

function simulateAsyncOperation(): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Operation Complete");
    }, 2000);
  });
}

Create a TypeScript function that retries a Promise-based operation up to 3 times if it fails.

async function retryOperation<T>(operation: () => Promise<T>, retries: number = 3): Promise<T> {
  let lastError;
  for (let i = 0; i < retries; i++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error;
    }
  }
  throw lastError;
}

Explain the concept of a Promise in JavaScript/TypeScript.

A Promise represents an asynchronous operation that can be in one of three states: pending, fulfilled, or rejected. It allows handling asynchronous operations in a more readable and manageable way compared to traditional callbacks.

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

  • Answer: TypeScript is a superset of JavaScript that adds static typing and other features to the language. It helps developers catch errors early through type checking, improves code readability, and facilitates better tooling. Unlike JavaScript, which is dynamically typed, TypeScript allows for static type definitions.

Explain the concept of “type inference” in TypeScript.

  • Answer: Type inference is the ability of TypeScript to automatically determine the type of a variable based on its initial value or usage. This reduces the need for explicit type annotations.
let x = 5; // TypeScript infers that x is of type number

How do you define a variable in TypeScript? Provide an example.

  • Answer: Variables in TypeScript are defined using let, const, or var keywords, with optional type annotations.
let name: string = "Alice";
const age: number = 30;
var isStudent: boolean = true;

What are “interfaces” in TypeScript, and how do you use them?

  • Answer: Interfaces in TypeScript define the shape of an object, describing the types of its properties. They are used for type-checking and ensuring that objects adhere to a specific structure.
interface Person {
  name: string;
  age: number;
  greet(): string;
}

const person: Person = {
  name: "Alice",
  age: 30,
  greet() {
    return `Hello, my name is ${this.name}`;
  }
};

How does TypeScript handle null and undefined values?

  • Answer: TypeScript has null and undefined types, and variables can be explicitly or implicitly assigned these values. By default, null and undefined are assignable to all types unless the --strictNullChecks option is enabled, which enforces strict checking.
let value: string | null = null;
value = "Hello";

What is the purpose of the “readonly” modifier in TypeScript?

  • Answer: The readonly modifier is used to mark properties as immutable, meaning their values cannot be changed after the initial assignment.
class Point {
  readonly x: number;
  readonly y: number;

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

const point = new Point(10, 20);
// point.x = 15; // Error: Cannot assign to 'x' because it is a read-only property.

Explain the concept of “generics” in TypeScript with an example.

  • Answer: Generics allow for the creation of reusable components that work with any data type. They provide a way to create flexible and type-safe code.
function identity<T>(arg: T): T {
  return arg;
}

let output1 = identity<string>("Hello");
let output2 = identity<number>(123);

How do you use “type aliases” in TypeScript? Provide an example.

  • Answer: Type aliases create a new name for a type, making the code more readable and maintainable.
type StringOrNumber = string | number;

let value: StringOrNumber;
value = "Hello";
value = 123;

What are “decorators” in TypeScript, and how are they used?

  • Answer: Decorators are special types of declarations that can be attached to a class, method, accessor, property, or parameter. They are used to modify the behavior of the target they are applied to.
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return `Hello, ${this.greeting}`;
  }
}

How does TypeScript handle asynchronous programming?

  • Answer: TypeScript handles asynchronous programming using Promises, async/await syntax, and other asynchronous patterns available in JavaScript.
function delay(ms: number) 
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function asyncCall() {
  console.log("Calling...");
  await delay(2000);
  console.log("Done!");
}

asyncCall();

What are “enums” in TypeScript, and how do you use them?

  • Answer: Enums allow for defining a set of named constants, making it easier to work with sets of related values.
enum Color {
  Red,
  Green,
  Blue
}

let c: Color = Color.Green;
console.log(c); // Output: 1

What is “namespace” in TypeScript, and how is it used?

  • Answer: Namespaces are used to organize code into logical groups and prevent name collisions.
namespace MyNamespace {
  export function sayHello() {
    console.log("Hello from MyNamespace");
  }
}

MyNamespace.sayHello();

How do you implement inheritance in TypeScript?

  • Answer: Inheritance is implemented in TypeScript using the extends keyword.typescript
class Animal {
  move(distance: number) {
    console.log(`Animal moved ${distance} meters`);
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof! Woof!");
  }
}

const dog = new Dog();
dog.bark();
dog.move(10);

How does TypeScript support “overloading” functions?

  • Answer: TypeScript allows function overloading by providing multiple function signatures for a single function.
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
  return a + b;
}

console.log(add(1, 2)); // Output: 3
console.log(add("Hello, ", "world")); // Output: Hello, world

Explain how error handling works with promises in TypeScript.

  • Answer: Error handling in promises can be done using the catch method or a try...catch block with async/await
myPromise
  .then(result => console.log(result))
  .catch(error => console.error(error));

// Using async/await
async function getData() {
  try {
    const data = await myPromise;
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

How do you define an interface in TypeScript?

  • Answer: An interface in TypeScript is defined using the interface keyword.typescript
interface Person {
  name: string;
  age: number;
}

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

How do you define optional properties in an interface?

  • Answer: Optional properties are defined using a question mark (?) after the property name.
interface Person {
  name: string;
  age?: number;
}

const person1: Person = { name: "Alice" };
const person2: Person = { name: "Bob", age: 30 };

How do you handle multiple asynchronous operations sequentially in TypeScript?

  • Answer: You can handle multiple asynchronous operations sequentially using async/await.
async function sequentialTasks() {
  const result1 = await asyncOperation1();
  const result2 = await asyncOperation2(result1);
  return result2;
}

sequentialTasks().then(result => console.log(result));

What is the purpose of the new keyword in interface definitions?

  • Answer: The new keyword in interface definitions is used to define a constructor signature.
interface ClockConstructor {
  new (hour: number, minute: number): ClockInterface;
}

interface ClockInterface {
  tick(): void;
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
  return new ctor(hour, minute);
giaic typescript exam subjective questions video
giaic objective questions video
TYPESCRIPT-NOTES

If you want to check you knowledge more please also check certificate 2 and certificate 3 as well..

governor sindh it course typescript quiz preparation (Certificate 2)

Answer These Amazing 8 Questions To Grab An E-Certificate On Typescript

Whether you’re a beginner or an experienced developer, this quiz is designed to challenge and enhance your TypeScript knowledge. Don’t miss out on this chance to learn, compete, and earn recognition!

governor sindh it course typescript quiz preparation (Certificate 3)

Answer These Amazing 20 Questions On Typescript

Featured Image

WELCOME TO TYPESCRIPT FUNDAMENTAL QUIZ FOR GOVORNOR SINDH IT COURSE STUDENTS

1. 
What is the output of the following TypeScript code? const foo = (): number => 5; console.log(foo());

2. 
JavaScript is a ____________________ synchronous programming language.

3. 
Which of the following is not a correct way to define variable in TypeScript

4. 
What is the value of result after executing the following TypeScript code? let result: string = ""; for (let i = 0; i < 5; i++) { result += i.toString(); }

5. 
What does the following TypeScript code snippet do? let isEven = (num: number): boolean => num % 2 === 0;

6. 
What is the syntax for defining a function in TypeScript?

7. 
What will be the result of the following TypeScript code? const x = 10; if (true) { const x = 20; console.log(x); } console.log(x);

8. 
What is the syntax error in the following TypeScript code? function concatStrings(a: string, b: number): string { return a + b;}

9. 
What is the purpose of the never type in the: function neverEnding() : never { while (true) {} }

10. 
What is the difference between “typeof” and “instanceof” in TypeScript?

11. 
What is the output of the following TypeScript code? let x = 5; x = ‘hello’; console.log(x);

12. 
What is the output of the following code: enum StatusCode { OK = 200, NotFound = 404, Error = 500 } console.log(StatusCode.NotFound);

13. 
What is the output of the following code: enum Color { Red, Green, Blue } console.log(Color.Green);

14. 
What is the cause of the syntax error in the following TypeScript code? lett message = "Hello World";//syntax error ; console.log(message);

15. 
Consider the following code: typescript // Module1.ts export const greeting = "Hello"; Which statement correctly imports the greeting variable from Module1.ts?

16. 
Definitely Typed is...

17. 
What is the difference between “==” and “===” in TypeScript?

18. 
What is the purpose of the never type in the: function neverEnding(): never { while (true) {} }

19. 
Identify the syntax error in the following TypeScript code: const colors: Array = ["red", "blue", 42];

20. 
What is the output of the following code: const arr = [1, 2, 3, 4, 5]; console.log(arr.slice(2));


THANK YOU SO MUCH FOR ATTEMPTING THE QUIZ

PLEASE DO SUBSCRIBE TO YOUTUBE CHANNEL MEHAK ALAMGIR FOR MORE.

 

Govornor Sindh IT Course Test Prepration Videos : Click Here

 



Govornor Sindh IT Course Onside Student Exam Preparation Video’s

Typescript Foundation Quiz Preparation (part 1)
Typescript Foundation Quiz Preparation (part 2)
Typescript Foundation Quiz Preparation (part 3)
Typescript Foundation Quiz Preparation (part 4)
Typescript Foundation Quiz Preparation (part 5)
Typescript Foundation Quiz Preparation (part 6)
Typescript Foundation Quiz Preparation (part 7)
Typescript Foundation Quiz Preparation (part 8)
Typescript Foundation Quiz Preparation (part 9)

Leave a Reply

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.