I have a function called
convertStudentObjectToStudentString
which is designed to iterate through a provided input (such as an object or array) and convert any instance of a Student
into a simple string.
I am uncertain about how to specify the input and output types for this function. When the function receives a Student, it can directly return a string. However, when given an object or array, it should return a similar object/array with the same keys unless the value is a Student object.
class Student {
name: string;
constructor(name: string) {
this.name = name;
}
}
const alice = new Student('Alice');
const bob = new Student('Bob');
const school = {
students: [
alice,
bob
],
chemistryClass: {
students: [alice]
},
prefect: bob,
}
function convertStudentObjectToStudentString<T>(input: T): T extends Student ? string : T {
if (input instanceof Student) return input.name;
if (typeof input !== 'object') return input;
if (Array.isArray(input)) return input.map(convertStudentObjectToStudentString);
return Object.keys(input).reduce((acc, k) => ({
...acc,
[k]: convertStudentObjectToStudentString(input[k]),
}), {});
}
console.log(school);
console.log(convertStudentObjectToStudentString(school));
// {
// "students": ["Alice", "Bob"],
// "chemistryClass": {
// "students": ["Alice"]
// },
// "prefect": "Bob"
// }
const physicsStudents = [bob, alice];
console.log(convertStudentObjectToStudentString(physicsStudents));
// [ "Bob", "Alice" ]
See the demonstration on: https://stackblitz.com/edit/typescript-sm5gqz