Let's see this example
Property 'description' has no initializer and is not definitely assigned in the constructor.
There are 3 ways:
- You can define default value for description when define this property. Eg: description: string = '';
- You can use exclaimation point ( ! ). Eg description!: string;
- You can set the default value for description in constructor function
class Example {
title: string;
createdAt: Date;
updatedAt: Date;
description!: string;
constructor(title: string) {
this.title = title;
const now = new Date();
this.createdAt = now;
this.updatedAt = now;
}
}
The reason is missing type definition for PropTypes. So you need to add a static property
All you need is to declare the component type properly to include the props type:
npm i prop-types
npm i @types/prop-types --save-dev
import React from 'react';
import PropTypes from 'prop-types';
import { Example } from './StateExample';
interface PropExampleProps {
example: Example;
}
export class PropExample extends React.Component<PropExampleProps> {
public static propTypes = {};
constructor(props: { example: Example }) {
super(props);
this.state = {
example: props.example
};
}
render() {
const { example } = this.state as { example: Example };
return (
<>
<p>{example.toString()}</p>
</>
);
}
}
PropExample.propTypes = {
example: PropTypes.any
};