I have an interface for a form values:
export interface FormProps {
name: string
customerIds: number[]
primaryColor: string
headingColor: string
websiteLink?: string
websiteLinkEnabled: boolean
contactLink?: string
contactLinkEnabled: boolean
instagramLink?: string
instagramLinkEnabled: boolean
facebookLink?: string
facebookLinkEnabled: boolean
logo: File[]
numberOfImages: number
}
I would like to check if the fields are dirty, by a function that takes an array of string that maps to each field and then check if there is a difference between the old and new values:
const colorsFields = ['primaryColor', 'headingColor']
checkIfFieldsAreDirty(colorsFields, initialValues, values)
const checkIfFieldsAreDirty = (fields: string[], initialValues: FormProps, values: FormProps): boolean => fields.some(field => initialValues[field] !== values[field]
But, I get a Typescript error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FormProps'. No index signature with a parameter of type 'string' was found on type 'FormProps'.
How can I fix this?
CodePudding user response:
You are using an array of string in order to access elements inside initialValues
, in order to do this, you have to pass an array of keyof FormProps
:
const colorsFields: (keyof FormProps)[] = ['primaryColor', 'headingColor']
An example here