Middle
Task 6: Write a generic function that accepts an object with a mandatory 'name' property of type string and returns a string with the entity's name.
sobes.tech AI
Answer from AI
Here's an example of a generic function in TypeScript that takes an object with a required property name of type string and returns a string with the name:
function getName<T extends { name: string }>(obj: T): string {
return obj.name;
}
// Example usage:
const user = { name: 'Ivan', age: 30 };
console.log(getName(user)); // Outputs: Ivan
The function is constrained by the type T, which must contain a name field of type string. This allows passing objects with additional properties while maintaining type safety.