1

I can't seem to fix some typescript error I get on my react app.

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"
                />
              )}
            />
)

Error:

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

Any idea how to fix this?

1
  • I thing application fails to fetch jobTItle or jobTitle is not array type Commented May 12, 2020 at 14:44

2 Answers 2

1

Without seeing the type definition of Autocomplete it's difficult to tell exactly, but it looks like the options property requires an array (of unknown type). For example:

type Options = unknown[];

This requires it to always be an array, even an empty array. The following code will not work:

let options: Options;
const data = { jobTitles: undefined };
options = data.jobTitles; // same error

You can resolve this by defaulting to an empty array in case jobTitles is not known, for example:

options={data?.jobTitles || []}

This behavior may be undefined, though -- you might have to refer to the Autocomplete library itself to see how to handle this properly.

Sign up to request clarification or add additional context in comments.

Comments

1

The options property on the Autocomplete component is expecting the prop to be of type unknown[]. You need to handle the case where data?.jobTitles is undefined. You should be able to just default it to an empty array if the value is undefined.

options={data?.jobTitles || []}

1 Comment

thank you this also works, althou the other answer is more explainable!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.