In Typescript, I have a nested object variable:
Sorry the previous example confused people. The value is not same as its key. I will provide a better example.
const obj = {
k1: {
k1A: "k1A_A",
k1B: "k2B_B",
k1C: {
k1C1: "k1C1_C",
k1C2: "k1C2_D",
},
},
k2: {
k2A: {
k2A1: "k2A1_E",
k2A2: "k2A2_F",
},
k2B: {
k2B1: "k2B1_G",
k2B2: "k2B2_H",
},
},
k3: {
k3A: 'K3A_I'
}
}
I have a function, which will lookup and ouput the deepest and nested object key path.
function getKeyPath(originalObj) {}
and the function runs like:
const keyPath = getKeyPath(obj)
and the output will be:
{
k1A: ["k1"],
k1B: ["k2B"],
K1C1: ["k1", "k1C"],
k1C2: ["k1", "k1C"],
k2A1: ["k2", "k2A"],
k2A2: ["k2", "k2A"],
k2B1: ["k2", "k2B"],
k2B2: ["k2", "k2B"],
k3A: ["k3"],
}
with Typescript, what I current have set is:
function getKeyPath<T>(originalObj:T):{
[x in string]: string[]
} {}
Is there a way, I can have a narrow type check? So instead of any string, I limit the return keys are from key of obj?
If I use type key = keyof typeof obj
, I can only get the first level of key, but not the deeper one.