class 属性 参数的自动类型推断
Automatic type inference for class property parameters
我正在使用一个名为 apprun. The Component class type defintion (here is 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;
}
当我在自己的组件中使用此 class 时,我遇到了类型推断问题:
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
的class属性:readonly state: T
。但是 view
只在你的代码中定义,没有类型定义,所以它的类型是从 view = (state) => <div>About</div>
声明中推断出来的,所以它是 (state: any) => JSX.Element
.
您应该在您自己的将从 Component
继承的组件 class 中定义 view: View<T>
,或者定义 state
参数的类型:state: State
.
我正在使用一个名为 apprun. The Component class type defintion (here is 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;
}
当我在自己的组件中使用此 class 时,我遇到了类型推断问题:
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
的class属性:readonly state: T
。但是 view
只在你的代码中定义,没有类型定义,所以它的类型是从 view = (state) => <div>About</div>
声明中推断出来的,所以它是 (state: any) => JSX.Element
.
您应该在您自己的将从 Component
继承的组件 class 中定义 view: View<T>
,或者定义 state
参数的类型:state: State
.