TS2322: Type 'object' is not assignable to

2019-03-03 12:54发布

问题:

I have a simple TypeScript Component where I try to implement type checking, but I cannot figure out what is wrong with the next part of code:

import React from 'react'
import { Provider } from 'react-redux'
import { Title } from '../components'
import { Props } from './types'

const AppContainer: React.SFC<Props> = ({ store }) => {
  return (
    <Provider store={store}>
      <Title />
    </Provider>
  )
}

export default AppContainer

Because I always gets an error:

TS2322: Type 'object' is not assignable to type 'Store'. Property 'dispatch' is missing in type '{}'.

Component Interface:

export interface Props {
  store: object,
  dispatch(): any,
  getState(): any,
  subscribe(): any,
  replaceReducer(): any
}

P.S. I admit, that Type checking works fine if I remove bracers from the argument store, like: const AppContainer: React.SFC<Props> = (store) => ...

回答1:

So:

P.S. I admit, that Type checking works fine if I remove bracers from the argument store, like: const AppContainer: React.SFC<Props> = (store) => ...

Yes, this is exactly right! So the solution in your case is a very easy:

const AppContainer = ({ store }: Props) => {
  return (
    <Provider store={store}>
      <Title />
    </Provider>
  )
}

This is because you declare your function arguments like in destructive way. If you will choose the non-destructive = (store) => you also can choose you own type-checking solution. It's not any different between both ways. You can choose one of them on you own.



回答2:

I think it should be capital O in object i.e. Object.

export interface Props {
  store: Object,
  dispatch(): any,
  getState(): any,
  subscribe(): any,
  replaceReducer(): any
}