0

I am stuck in converting the flatten function into typescript. Code sample is given below. I am stuck at giving type to function argument ob.

// Declare an object
let ob = {
    Company: "GeeksforGeeks",
    Address: "Noida",
    contact: +91-999999999,
    mentor: {
        HTML: "GFG",
        CSS: "GFG",
        JavaScript: "GFG"
    }
};

// Declare a flatten function that takes
// object as parameter and returns the
// flatten object
const flattenObj = (ob) => {

    // The object which contains the
    // final result
    let result = {};

    // loop through the object "ob"
    for (const i in ob) {

        // We check the type of the i using
        // typeof() function and recursively
        // call the function again
        if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
            const temp = flattenObj(ob[i]);
            for (const j in temp) {

                // Store temp in result
                result[i + '.' + j] = temp[j];
            }
        }

        // Else store ob[i] in result directly
        else {
            result[i] = ob[i];
        }
    }
    return result;
};

console.log(flattenObj(ob));

Any help in converting this function into typescript will be highly appreciated.

  • You need help to create interface for `ob`? – Nitheesh Sep 07 '22 at 11:26
  • Did you try? const flattenObj(ob: any){ } – HoangHieu Sep 07 '22 at 11:28
  • https://www.typescriptlang.org/docs/handbook/functions.html#overloads – HoangHieu Sep 07 '22 at 11:29
  • type (paste) your javascript code in a typescript editor and hover over the variable (`ob` in this case) and you'll see the typescript-inferred type for that variable, which is a good starting point for explicitly setting the type - this even works in typescript playground. – kikon Sep 07 '22 at 11:32
  • `(ob: Record)` and `let result:Record = {};` – Keith Sep 07 '22 at 11:34
  • @Nitheesh, I can create interface for `ob`. But the main issue is with recursion function `flattenObj`. I am not getting how can I set the thpe that works for initial call and also the recursive call. – Malik Lakhani Sep 07 '22 at 12:24

0 Answers0