简体   繁体   中英

Typescript type checking error how to fix in React

I have the following code:

const [fetchJobTitlesCall, { data }] = useLazyQuery<Jobtitles, JobtitlesVariables>(JobTitlesQuery)
useEffect(() => {
    fetchJobTitlesCall({ variables: { keyword: 'Dev' } })
}, [fetchJobTitlesCall, data])

return (
            <Autocomplete
              onChange={(event, value) => dispatchJobTitlesFilter(value)}
              multiple
              id="tags-outlined"
              options={data?.jobTitles} // this line throwing error
              getOptionLabel={option => option.name + ` (${option.totalApplicants})`} // this line throwing error
              filterSelectedOptions
              renderInput={params => (
                <TextField
                  {...params}
                  onChange={event => fetchJobTitles(event.target.value)}
                  variant="outlined"
                  label="Search Job Title"
                  placeholder="Search Job Title"
                />
              )}
            />
)

The error I get is:

Type 'Jobtitles_jobTitles | undefined' is not assignable to type 'unknown[]'. Type 'undefined' is not assignable to type 'unknown[]'.

Can anyone explain why I am getting the error?

It seems like typescript wants you to pass some kind of variable having data type other than undefined. The issue seems to be with

options={data?.jobTitles}

What it essentially does is it will check for key "jobTitles" in data and assign it's content to options if it exist, otherwise assign undefined(which is not the right thing in this case)

const [fetchJobTitlesCall, { data }] = useLazyQuery<Jobtitles, JobtitlesVariables>(JobTitlesQuery)
useEffect(() => {
    fetchJobTitlesCall({ variables: { keyword: 'Dev' } })
}, [fetchJobTitlesCall, data])

return (
            <Autocomplete
              onChange={(event, value) => dispatchJobTitlesFilter(value)}
              multiple
              id="tags-outlined"
              options={data.jobTitles ? data.jobTitles : {}} // Modified code
              getOptionLabel={option => option.name + ` (${option.totalApplicants})`} // this should be automatically fixed
              filterSelectedOptions
              renderInput={params => (
                <TextField
                  {...params}
                  onChange={event => fetchJobTitles(event.target.value)}
                  variant="outlined"
                  label="Search Job Title"
                  placeholder="Search Job Title"
                />
              )}
            />
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM