1
votes

New to Typescript and have most of my errors resolved, but I'm not sure what to do about this one. Given this component...

const CurrentUser: React.SFC = props => (
  <Query {...props} query={CURRENT_USER_QUERY}>
    {payload => props.children(payload)}
  </Query>
)

I'm seeing these errors. I don't understand how children could ever be null or undefined. Aren't they guaranteed if the object is an SFC? How do I resolve this?

Cannot invoke an object which is possibly 'null' or 'undefined'

enter image description here

Update 3/3/2019

Because of BlackICE's comment, I eventually realized that I needed to check that children exists before I invoke it. Duh! But now I have a different problem

Cannot invoke an expression whose type lacks a call signature. Type 'string | number | true | {} | ReactElement | ReactNodeArray | ReactPortal' has no compatible call signatures.

enter image description here

1
that ? after the name of children property on props means it can be null.BlackICE
@BlackICE True, but why would that be? I guess if it were a self closing component <CurrentUser /> it could be, but since this is a render prop, that should never be. Any idea how to fix this?Chris Geirman
Why do you think that SFC can't be used as self-closing?Cerberus
I didn't say it couldn't. I realized if it we're, children would be nullChris Geirman

1 Answers

2
votes

For those interested, here is the final solution...

type Props = {
  children: (a: QueryResult) => JSX.Element
}

const CurrentUser: React.SFC<Props> = props => (
  <Query {...props} query={CURRENT_USER_QUERY}>
    {payload => props.children && props.children(payload)}
  </Query>
)

where QueryResult is imported from react-apollo

import { Query, QueryResult } from 'react-apollo'