Sobes.tech
Middle

/** * Task 1: Generics and Key Type Safety * Create a function `getProperty` that takes an object and a key. * Use generics to ensure the function is type-safe, and the key exists on the object. */ function getProperty<T extends Record<string, unknown>, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } getProperty('str', 'toString') /** * Task 2: Given multiple Todo interface declarations below, explain what happens when they are present in the same scope. * Discuss how TypeScript treats them and fill in the `myTodo` object to satisfy the merged Todo interface requirements. */ interface Todo { title: string; dueDate: Date; } interface Todo { description: string; completed: boolean; }

sobes.tech AI

Answer from AI

Task 1: The getProperty function uses generics and the constraint K extends keyof T to ensure that the key exists in the object obj of type T. This guarantees type-safe access to the object's properties.

Example function:

function getProperty<T extends Record<string, unknown>, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const result = getProperty({name: 'Alice', age: 30}, 'name'); // type string

Calling getProperty('str', 'toString') is valid because strings have a toString method.


Task 2: In TypeScript, multiple interface declarations with the same name in the same scope are merged. This means the resulting Todo interface will contain all properties from both declarations:

interface Todo {
  title: string;
  dueDate: Date;
  description: string;
  completed: boolean;
}

To make the object myTodo conform to the merged interface, all these properties must be defined:

const myTodo: Todo = {
  title: 'Learn TypeScript',
  dueDate: new Date('2024-12-31'),
  description: 'Study advanced TypeScript features',
  completed: false
};

Thus, interface declarations in TypeScript can be extended by re-declaring them, which is convenient for gradually adding properties.

/** * Task 1: Generics and Key Type Safety * Create a… - sobes.tech