TypeScript Version: 2.8.1
Search Terms: this Types, Complex Generics
Code
import * as React from 'react';
import { Component, ReactNode, ComponentClass } from 'react';
import { State } from '@xialvjun/state';
export class Context<S> extends State<S> {
abc: Array<this> = [this]
// Since `abc: Array<this>` is OK, then why `Consumer: ComponentClass<{ children: (context: this) => ReactNode }>` is wrong ?
Consumer: ComponentClass<{ children: (context: this) => ReactNode }> = (() => {
// Consumer = (() => {
const self = this;
// why here this type is not accessible ?
return class ContextConsumer extends Component<{ children: (context: typeof self) => ReactNode }> {
// return class ContextConsumer extends Component<{ children: (context: Context<S>) => ReactNode }> {
boundForceUpdate = () => this.forceUpdate()
unsubscribe: () => void
componentDidMount() {
this.unsubscribe = self.onChange(this.boundForceUpdate);
}
componentWillUnmount() {
this.unsubscribe()
}
render() {
return this.props.children(self);
}
}
})();
}
Expected behavior:
No error
Actual behavior:
Error: A 'this' type is available only in a non-static member of a class or interface.
I am not quite sure i follow the issue description..the use of this in an object literal is not allowed anyways, it has to be within a class or an interface or type alias.. so the correct way to do this is:
type myComponentClass<T> = ComponentClass<{ children: (context: T) => ReactNode }>;
export class Context<S> extends State<S> {
abc: Array<this> = [this]
// Since `abc: Array<this>` is OK, then why `Consumer: ComponentClass<{ children: (context: this) => ReactNode }>` is wrong ?
Consumer: myComponentClass<this> = (() => { ... }
}
not sure i really understand the issue beyond that.
Awesome!
Thank you very much. That's just what I need. Thanks.
Most helpful comment
I am not quite sure i follow the issue description..the use of
thisin an object literal is not allowed anyways, it has to be within a class or an interface or type alias.. so the correct way to do this is:not sure i really understand the issue beyond that.