在React中使用useState将对象添加到数组时出现Typescript错误

时间:2020-09-04 17:12:46

标签: reactjs typescript react-hooks

结果类型prop定义如下。 CalendarProp,ContactProp ......是预定义的,并且都具有不同的类型。

type ResultProp =
    | { type: "calendar", data: CalendarProp }
    | { type: "contact", data: ContactProp }
    | { type: "dropbox", data: DropboxProp }
    | { type: "slack", data: SlackProp }
    | { type: "tweet", data: TweetProp }

日历道具

interface CalendarProp {
    id: string,
    title: string,
    invitees: string,
    date: string,
    matching_terms: Array<string>
}

ContactProp类型

interface ContactProp {
    id: string,
    name: string,
    company: string,
    emails: Array<string>,
    phones: Array<string>,
    last_contact: string,
    matching_terms: Array<string>
}

所有道具的类型都不同。 维护结果数组的组件在下面定义。使用useState挂钩将对象添加到结果数组时,出现Typescript错误。 这里的calendarData.calendar,...是json对象的数组。

const SearchResults: React.FC<QueryProp> = (props) => {
    const query = props.query;
    const [result, setResult] = useState<Array<ResultProp>>([]);
    
    useEffect(() => {
        if (query.length > 0){
            const files = [
                {
                    type: "calendar",
                    data: calendarData.calendar
                },
                {
                    type: "contact",
                    data: contactData.contacts
                }, 
                {
                    type: "dropbox",
                    data: dropboxData.dropbox
                },
                {
                    type: "slack",
                    data: slackData.slack
                },
                {
                    type: "tweet",
                    data: tweetData.tweet
                }
            ];

            for(const file of files){
                for(const d of file.data){
                    if (d.matching_terms.includes(query)) {
                        switch(file.type) {
                            case "calendar":
                                setResult([...result, { type: "calendar", data: d }]); // Error here
                                break;
                        }
                    }
                }
            }
        }
        return () => {
            setResult([]);
        }
    }, [query])

    return (
        <div className="search-results">
            {/* {result.map((r, index) => {
                return <Cardview key={index} {...r} />
            })} */}
        </div>
    )
}

我收到以下错误消息:

Argument of type '({ type: "contact"; data: ContactProp; } | { type: "dropbox"; data: DropboxProp; } | { type: "slack"; data: SlackProp; } | { type: "tweet"; data: TweetProp; } | { ...; })[]' is not assignable to parameter of type 'SetStateAction<ResultProp[]>'.
  Type '({ type: "contact"; data: ContactProp; } | { type: "dropbox"; data: DropboxProp; } | { type: "slack"; data: SlackProp; } | { type: "tweet"; data: TweetProp; } | { ...; })[]' is not assignable to type 'ResultProp[]'.
    Type '{ type: "calendar"; data: { id: string; title: string; invitees: string; matching_terms: string[]; date: string; } | { id: string; name: string; company: string; emails: string[]; phones: string[]; matching_terms: string[]; last_contact: string; } | { ...; } | { ...; } | { ...; } | { ...; }; }' is not assignable to type 'ResultProp'.
      Types of property 'data' are incompatible.
        Type '{ id: string; title: string; invitees: string; matching_terms: string[]; date: string; } | { id: string; name: string; company: string; emails: string[]; phones: string[]; matching_terms: string[]; last_contact: string; } | { ...; } | { ...; } | { ...; } | { ...; }' is not assignable to type 'CalendarProp'.
          Type '{ id: string; name: string; company: string; emails: string[]; phones: string[]; matching_terms: string[]; last_contact: string; }' is missing the following properties from type 'CalendarProp': title, invitees, date

1 个答案:

答案 0 :(得分:1)

在这里,您测试来自file的{​​{1}}与files类型是否匹配。但是您从未对TypeScript说过calendar的类型。对于他来说,不确定files到底是什么,因此可以是dCalendarProp或...您有2种解决方案来解决此问题:

  1. 声明ContactProp的类型:
files

在这种情况下,如果const files: ResultProp[] = [ ... file.type,则TypeScript可以推断出"calendar"的类型为data


  1. CalendarProp的值设置为d
CalendarProp