Reputation: 561
I am new to Typescript, and I trying to write React with Typescript.
I see a demo as below.
I'm confused about the <Props, State>
in the class declaration. I think it is just generic, but this make no sense. Dose it has any relation with the type Props
and type State
above?
import * as React from 'react';
type Props = {
label: string;
};
type State = {
count: number;
};
export class ClassCounter extends React.Component<Props, State> {
readonly state: State = {
count: 0,
};
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
const { handleIncrement } = this;
const { label } = this.props;
const { count } = this.state;
return (
<div>
<span>
{label}: {count}
</span>
<button type="button" onClick={handleIncrement}>
{`Increment`}
</button>
</div>
);
}
}
Upvotes: 0
Views: 259
Reputation: 368
React.Component<Props, State>
is the "passing in" you describe, this is not declaring generics (which has similar syntax).
It's the same relationship as foo(x, y)
has to function foo(x, y) {}
.
In the former, you're passing in the variables named x
and y
into the function foo
.
In the latter, you're declaring a function foo
that expects two variables to be passed in, and it going to refer to them inside the function as x
and y
.
Equivalently, type React.Component<Props, State> =
would be declaring, and class Xx extends React.Component<Props, State> {
is saying "here, use these types called Props
and State
that I've defined elsewhere".
Upvotes: 1