TypeScript - check a variable of type unknown has certain property

Viewed 352

I'm using typescript in relay and the props passed down is of type unknown. I have tried several ways to convince the compiler that it can have some property but it keeps showing me an error:

<QueryRenderer
  environment={environment}
  query={testQuery}
  variables={{}}
  render={({ error, props }) => {
    if (error) {
      return <div>Error!</div>;
    }
    if (!props) {
      return <div>Loading...</div>;
    }
    if (!!props && _.isObject(props) && props.hasOwnProperty("Messages"))
      return <MessageList messages={props.Messages} />;
  }}
/>;

The above code doesn't work, typescript still warns me that

Property 'Messages' does not exist on type 'object'.

How to make this simple example work yet not make my code look hideous? Many thanks!

1 Answers

You should annotate the specific GraphTaggedNode from your query. This will be your query's name from your testQuery variable. In my example below I have called it TestQuery. But it should be prefixed with the FileName_Query in pascal case.

Your props should now be annotated with TestQueryResponse.

<QueryRenderer<TestQuery>
  ...
 />
Related