I have the code like below
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 am getting 'input.conditional' is possibly 'undefined' error at input.conditional.filter((arrItem) => console.log(arrItem)).
How to get rid of this error? I cannot use non-null assertion or optional chaining . I cannot change the type either.
I thought I could do this by using "Type Guards" & I assume I am doing that at if ('conditional' in input) but apparently not. Can anyone help?
>Solution :
Ditch the in operator and just check if the input.conditional is set, the classic way.
const func = (input: FormItemDataType) => {
if(input.conditional) { // 👈 tells TypeScript that input.conditional under this block must be set
input.conditional.filter((arrItem) => console.log(arrItem));
}
};
