Below is the code snippet I am working with:
export type ConditionalItemType = [
{ condition: string },
{ [key: string]: FormItemDataType }
];
export type ConditionalItemDataType = ConditionalItemType[];
export type FormItemDataType = {
required: boolean;
type: string;
constraint?: TextConstraintType;
options?: string[];
conditional?: ConditionalItemDataType;
};
export type TextConstraintType = {
min?: number;
max?: number;
format?: string;
};
const obj: FormItemDataType = {
required: true,
type: 'select',
options: ['simple', 'complicated'],
conditional: [
[
{ condition: 'complicated' },
{
'How Complicated': {
required: true,
type: 'text',
constraint: {
max: 30,
},
},
},
],
],
};
const func = (input: FormItemDataType) => {
if ('conditional' in input) {
input.conditional.filter((arrItem) => console.log(arrItem));
} else null;
};
I'm encountering an error stating
'input.conditional' is possibly 'undefined'
at input.conditional.filter((arrItem) => console.log(arrItem))
.
Is there a way to resolve this issue without using non-null assertion
or optional chaining
? Altering the type is also not an option.
I attempted to apply "Type Guards" by checking if ('conditional' in input)
, but it seems that approach is not successful. Any suggestions?