Reputation: 556
Lets assume that I have
// Foo.js
type PropsType = { cool: boolean };
class Foo extends React.Component<PropsType> {}
// Bar.js
import Foo from './Foo';
type PropsBar = { temp: string };
class Bar extends Foo {
test() {
this.props.cool; // there is no error
this.props.temp;
^^^^ Property not found in object type
}
}
My question is, how to pass additional Props
to Bar
component?
Upvotes: 2
Views: 263
Reputation: 31823
You need to make your super class generic. Just as React.Component
is generic, so can your classes and functions be as well.
You can make a declaration such as a class or function generic by introducing a type parameter.
Let us make Foo
generic
export default class Foo<T> extends React.Component<FooProps & T> {}
Note the intersection type, written FooProps & T
, that is passed to the generic super class React.Component
. This means that Foo.prototype.props
will have the properties declared in FooProps
and also any properties declared by T
.
Now when we use Foo
, such as in an extends
clause, we need to specify a type for T
.
type BarProps = { temp: string };
export default class Bar extends Foo<BarProps> {
constructor(props, context) {
super(props, context);
console.log(this.props.temp);
}
}
If you want to maintain simplicity for consumers of Foo
that do not add additional props, you can specify a default type for T
as in
export default class Foo<T = {}> extends React.Component<FooProps & T> {}
export class Bar extends Foo {}
Note: All of the syntax above is valid in both Flow and TypeScript.
Upvotes: 2