andy mccullough
andy mccullough

Reputation: 9571

Typescript and GraphQL mismatch types between graphql response and typescript type

I am using typescript, react-apollo and AWS Appsync for a react app I am building, but running into typescript warnings which I'm not sure where I am going wrong.

I have a graphql schema that looks like -

schema {
    query: Query
}

type Query {
    events: [Event]
}

type Event {
   ...
}

I am using useQuery to return all events, like -

const {
   loading: eventsListLoading,
   error: eventsListError,
   data: eventsListData
} = useQuery(EVENTS_LIST_HOME);

EVENTS_LIST_HOME comes from -

export const EVENTS_LIST_HOME = gql`
    query eventsListHome{
        events {
            title
        }
    }
`;

and I am trying to render the items like -

<table>
   {
      eventsListData.events.map((event: IEvent) => (
         <tr>
             <td>{event.title}</td>
         </tr>
      ))
   }
</table>

where I have a typescript interface IEvent

export default interface IEvent {
    title: string;
}

but I am getting the error -

enter image description here

I have tried renaming the typescript type to Event instead of IEvent and adding the other args, index and array, even though they are not used, but same error

What am I missing? How do I use the grapghql type of Event in typescript?

Upvotes: 1

Views: 1414

Answers (1)

manjunatha_d
manjunatha_d

Reputation: 319

You should use apollo codegen to generate TypeScript types for the types declared in your graphql schema - https://github.com/apollographql/apollo-tooling#apollo-clientcodegen-output.

It looks like there is a type mismatch between Event and IEvent. Can't say much without seeing the definition of Event.

Using the types generated by apollo codegen should fix the type errors.

Upvotes: 2

Related Questions