Search code examples
reactjstypescriptionic-frameworkjsxreact-props

Getting TypeScript compile error when attempting prop drilling of state objects in Ionic/React


I’m trying to drill app state down through component props in app.tsx, but get a typescript error:

Type '{ dailyObd: RouteComponentProps<any, StaticContext, {}>; }' is not assignable to type 'IntrinsicAttributes & obds & { children?: ReactNode; }'.
  Property 'dailyObd' does not exist on type 'IntrinsicAttributes & obds & { children?: ReactNode; }'.ts(2322)

It points to the source of the error being "dailyObd" in <Today dailyObd... in App's return.

Here’s a breakdown of what I’ve got: app.tsx:

const App: React.FC = () => {
  const [dailyObds, setDailyObds] = useState<dailyObds>([{
    title: 'First',
    completed: false
  }])

  return (
    <IonApp>
      <IonReactRouter>
        <IonSplitPane contentId="main">
          <Menu />
          <IonRouterOutlet id="main">
            <Route path="/page/today" render={(dailyObds)=>(<Today dailyObd={dailyObds} /> )} />
            <Redirect from="/" to="/page/Inbox" exact />
          </IonRouterOutlet>
        </IonSplitPane>
      </IonReactRouter>
    </IonApp>
  )
}

interface dailyObd{
    title: string
    completed: boolean
}
interface dailyObds extends Array<dailyObd>{}

export default App;

Here’s Today.tsx:

const Today: React.FC = ({ dailyObd })=>{
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start"><IonMenuButton /></IonButtons>
          <IonTitle>Today</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <IonText>Some stuff will go here... eventually.</IonText>>
      </IonContent>
    </IonPage>
  )
}
export default Today

I set strict to false in tsconfig.json, but I still can’t compile because of the listed error. What am I missing here? Why is it seemingly so difficult to add a prop to a component with TypeScript? Thanks for any help, I am new to Ionic/React/TypeScript.


Solution

  • You need to provide the typings for your Today component. From what I can see, the Today component accepts dailyObd as the props, so you will need to create an interface or type genetic for the component.

    In addition, you might want to rename your dailyObd interface to use upper camelcase instead, as this is one of the naming conventions for classes/interfaces.

    interface DailyObd {
      title: string;
      completed: boolean;
    }
    

    Now, you can provide the generic type parameter for Today.

    interface TodayProps {
      dailyObd: DailyObd[];
    }
    
    const Today: React.FC<TodayProps> = ({ dailyObd }) => { ... }