Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kiprasbiel's avatar

Typescript making sure optional parameters are set

So I have these two typescript interfaces:

interface SourceTypeJsonType {
  /*....*/
  child?: SourceTypeNestedObject;
}

interface SourceTypeNestedObject {
  [key: number]: SourceTypeJsonType;
}

And in this simple function I try to check if object has child parameter. But for some reason I still get an TS error Argument of type 'SourceTypeNestedObject | undefined' is not assignable to parameter of type 'SourceTypeNestedObject'.

function flatten(obj: SourceTypeNestedObject) {
      for (const key in obj) {
        sourceTypes.value[obj[key]["source_type_id"]] = obj[key];
        if (typeof obj[key].child !== "undefined") {
          flatten(obj[key].child); // Error: TS2345: Argument of type 'SourceTypeNestedObject | undefined' is not assignable to parameter of type 'SourceTypeNestedObject'.   Type 'undefined' is not assignable to type 'SourceTypeNestedObject'.
        }
      }
    }

If I understand correctly I shouldn't get this error because I check if typeof obj[key].child !== "undefined". What am I doing wrong here?

Note

If I make child property mandatory, the error goes away, but that would be wrong, because data received might not have child parameter.

0 likes
0 replies

Please or to participate in this conversation.