After creating a type guard to verify if an object is of a specific type, I encountered a type error when trying to use array find with the type guard and a second condition. Strangely, the error disappears when I use array find with the type guard alone followed by find.
Here is the type guard:
const isHtmlField = (
field: GravityForms.Field
): field is GravityForms.HtmlField => {
return field.type === 'html'
}
The code snippet below triggers a type error:
const description: GravityForms.HtmlField | undefined = fields.find(
(item) => {
isHtmlField(item) && item.label.toLowerCase() === "description";
}
);
However, the following code works without any issues:
const description: GravityForms.HtmlField | undefined = fields
.filter(isHtmlField)
.find((item) => item.label.toLowerCase() === "description");
In my types.d.ts file, the type definitions are as follows:
declare namespace GravityForms {
// Type definitions here
}
interface FormPage {
// FormPage interface definition here
}
type FormPages = FormPage[];
type UpdateDataItem = (id: string, value: string) => void;
interface FormSubmissionData {
// FormSubmissionData interface definition here
}
The complete page component where I'm trying to use the description field can be seen below:
const Page: FC<IPage> = ({ title, fields, hidden, incrementPage }) => {
// Component code here
};