This question should be an easy riddle for TypeScript/React hackers.
I have a React component that passes a class-object to a child-component. Within the child-component, I call a method on the class-object. Those two components look as follows:
class ParentComponent extends React.Component<{}, Foo> {
constructor(props: any) {
super(props);
this.state = new Foo();
}
render() {
return (<ChildComponent {...this.state} />);
}
}
class ChildComponent extends React.Component<Foo, {}> {
render() {
this.props.fooMethod(); // TypeError or not? fooMethod is not a function?
return (<div/>);
}
}
Furthermore, I have two different implementations of Foo
.
One of them works, whereas the other one throws a TypeError in the child-component.
Can you explain why only one of those Foo implementations works?
First Foo implementation:
class Foo {
constructor() {
this.fooMethod = function(): void {};
}
fooMethod: () => void;
}
Second Foo implementation:
class Foo {
fooMethod(): void {};
}