1import * as React from 'react';
2
3export interface TestProps {
4 count: number;
5}
6
7export interface TestState {
8 count: number;
9}
10
11class Test extends React.Component<TestProps, TestState> {
12 state = { count:0 }
13 render() {
14 return ( <h2>this is test</h2> );
15 }
16}
17
18export default Test;
1// Class Component React TypeScript ( with props and state usage ):
2
3import React, { Component } from 'react';
4
5type Props = { head ?: string , age ?: number };
6
7type State = { num: number };
8
9type DefaultProps = { head : string, age : string }
10/* <Props, State, DefaultProps> tell that
11these initialised types will be used in the class. */
12class Counter extends Component <Props, State, DefaultProps> {
13
14/* Default props appear when no value for the prop
15is present when component is being called */
16
17
18 static defaultProps : DefaultProps = {
19 head: "Heading is Missing",
20 age: "Age is missing",
21 };
22// Always write state above the render() method.
23 state: State = {
24 num: 0,
25 };
26
27 render() {
28
29 const add = () => this.setState({ num: this.state.num + 1 }) ;
30
31 return (
32 <div>
33 <h1> { this.props.head } </h1>
34 <p> Age: { this.props.age } </p> <br />
35 <h3> { this.state.num } </h3>
36 <button onClick={add}>Add 1</button>
37 </div>
38 );
39 }
40}
41
42export default Counter;