不能将类型“ {}”分配给类型“ Readonly <helloprops>”

时间:2018-08-25 10:14:46

标签: javascript typescript mobx mobx-react

我正在尝试将存储注入组件中,但似乎无法正常工作。
这是课程

import * as React from 'react';
import { inject, observer } from 'mobx-react';

import { FlightStore } from '../stores/FlightStore';

export interface HelloProps {
   flightStore: FlightStore
}



@inject('flightStore')
@observer
class Hello extends React.Component<HelloProps, any> {

constructor(props: HelloProps) {
    super(props);
    this.state = {
        //
    }
}


componentWillMount() {
    this.props.flightStore.getData();
}

render() {
    return (
        <div>

        </div>
    )
}
}

export default Hello;

它说Type '{}' is not assignable to type 'Readonly<HelloProps>'. Property 'flightStore' is missing in type '{}',这使我感到困惑,因为我没有在任何地方声明任何数据类型,所以我不知道发生了什么。

这是商店

import { action, observable } from 'mobx';
import *  as $ from 'jquery' ;


export class FlightStore {

@observable dataJ: any;

constructor() {
    //
}

@action getData() {

    $.ajax({
        url: 'https://www.kayak.com/h/mobileapis/directory/airlines',
        dataType: 'json',
        cache: false,
        success: (data: any) => {
            this.dataJ = data;
            console.log(data)
        },
        error: (xhr: any, status: any, err: any) => {
            console.log(err);
        }
    })
    console.log('I´m in getData')
}

}

这很奇怪,因为当我尝试输入“?”时在班上

export interface HelloProps {
  flightStore?: FlightStore
}

它表示ComponentWillMount()中的this.props.flightStore => [ts] Object is possibly 'undefined'.

更新

是的,当我尝试使用<Hello/>组件而不传递道具时会发生错误,因为我使用的是Mobx。
索引应用

import * as React from 'react';
import Hello from './components/Hello';

import stores from './stores'; 
import { Provider } from 'mobx-react';


 export default class App extends React.Component {
 render() {
    return (
        <Provider {...stores}>
            <div>
                <Hello />
            </div>
        </Provider>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

我假设当您尝试将组件用作<Hello/>而不传递道具时发生了原始错误。 Hello被声明为需要flightStore道具。您希望@inject会提供它,而TypeScript会知道您不必自己传递它,但这似乎行不通。因此,请看declaration of @inject

// Ideally we would want to return React.ComponentClass<Partial<P>>,
// but TS doesn't allow such things in decorators, like we do in the non-decorator version
// See also #256
export function inject(
    ...stores: string[]
): <T extends IReactComponent>(target: T) => T & IWrappedComponent<T>
export function inject<S, P, I, C>(
    fn: IStoresToProps<S, P, I, C>
): <T extends IReactComponent>(target: T) => T & IWrappedComponent<T>

如果转到referenced issue,您会发现问题尚未解决,并且有一些建议的解决方法。其中之一是,如在第二个版本中所做的那样,将prop声明为可选的,然后在访问它时使用非空断言:this.props.flightStore!