类属性参数的自动类型推断

时间:2019-04-10 07:38:08

标签: javascript typescript inferred-type

我正在使用一个名为apprun的库。 Component类的类型定义(这里是its implementation)如下:

  export type View<T> = (state: T) => string | VNode | VNode[] | void;

  export class Component<T=any> {
    constructor(state?: T, view?: View<T>, update?: Update<T>);
    readonly state: T;
    setState(state: T, options?: { render?: boolean, history?: boolean }): void;
    mount(element?: Element, options?: { render?: boolean, history?, global_event?: boolean }): Component<T>;
    start(element?: Element, options?: { render?: boolean, history?, global_event?: boolean }): Component<T>;
    on(name: string, fn: (...args: any[]) => void, options?: any): void;
    run(name: string, ...args: any[]): number;
    rendered: (state: T) => void;
    mounted: (props: any) => void;
    unmount: () => void;
    unload: () => void;
  }

当我在自己的组件中使用此类时,类型推断存在问题:

interface State {
  foo: string
}

export class AboutPage extends Component<State> {
  // State is correctly inferred.
  // Changing `foo` to be `1` will cause an error.
  state = {
    foo: 'bar'
  }

  // Parameter `state` implicitly has an 'any' type.
  // Why is the parameter not inferred just like the `state` property?
  view = (state) => <div>About</div>
}

我遇到的麻烦是理解为什么推断属性state的类型,为什么对参数state不会发生相同的事情?

1 个答案:

答案 0 :(得分:1)

这是因为state被定义为Component的类属性:readonly state: T。但是view仅在您的代码中定义,没有类型定义,因此它的类型是从view = (state) => <div>About</div>声明中推断出来的,因此它是(state: any) => JSX.Element

您应在自己的将从view: View<T>继承的Component类中定义Component,或定义state自变量的类型:state: State