我正在使用一个名为 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
没有发生同样的事情?
最佳答案
那是因为state
定义为Component
的类属性:readonly state: T
。但是view
仅在您的代码中定义,其中没有类型定义,因此它的类型是从 view = (state) => <div>About</div>
推断出来的声明,所以是 (state: any) => JSX.Element
.
您应该定义view: View<T>
在您自己的 Component 类中,该类将从 Component
继承,或定义 state
的类型参数:state: State
.
关于javascript - 类属性参数的自动类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55607173/