繁体   English   中英

Typescript 类型检查错误如何在 React 中修复

[英]Typescript type checking error how to fix in React

我有以下代码:

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

我得到的错误是:

键入“职位名称_职位名称 | undefined' 不能分配给类型 'unknown[]'。 类型“未定义”不可分配给类型“未知 []”。

谁能解释我为什么会收到错误?

似乎 typescript 希望您传递某种具有未定义数据类型的变量。 问题似乎与

选项={数据?.jobTitles}

它本质上所做的是它将检查数据中的关键“jobTitles”并将其内容分配给选项(如果存在),否则分配未定义(在这种情况下这不是正确的事情)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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