Feb 8, 2023
0
Level 2
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.
Please or to participate in this conversation.