Home > Software design >  TypeScript nested objects type definition
TypeScript nested objects type definition

Time:12-06

I want to define the interface Obj to match the objects structure below in the console.log

interface Obj {
  [key: string]: number or {} // <-------- don't know how to define
}

const returnNestedProp = (obj: Obj) => {
  return obj?.a?.b;
};


console.log(returnNestedProp({ a: 1 }));
console.log(returnNestedProp({ a: { b: { c: 3 } } }));
console.log(returnNestedProp({ b: { a: 1 } }));
console.log(returnNestedProp({ a: { b: 2 } }));

in Typescript. don't know hot to define the interface when I have an object or a number. Nested objects

CodePudding user response:

I think you want a tree type like this:

interface Obj {
  [key: string]: number | Obj
}

That means that each property of Obj may be number, or it may be another Obj. This allows for tree like nesting to an practically infinite depth.

Then to drill into that, you only need to check if it is typeof obj.someProp === 'object'. If that returns true, then Typescript knows that this property is an Obj and not a number.

const returnNestedProp = (obj: Obj) => {
  if (typeof obj.a === 'object') {
    return obj.a.b;
  }
  return
};

Test to prove that works:

console.log(returnNestedProp({ a: 1 })); // undefined
console.log(returnNestedProp({ a: { b: { c: 3 } } })); // { c: 3 }
console.log(returnNestedProp({ b: { a: 1 } })); // undefined
console.log(returnNestedProp({ a: { b: 2 } })); // 2

See Playground

CodePudding user response:

You can use a union type and the indexed access operator, like this:

interface Obj {
  [key: string]: number | { [key: string]: number | {} }
}
  • Related