I created a simple class component with some props. Since Typescript 3 and above, they state that defaultProps by default will use the same Interface as the component's props itself. reference
In the following code example, you can see I created a component, extending React.PureComponent with a given interface. One prop is called boolean with type boolean.
Then I got the static defaultProps
assignment where I made an "accidental" typo where I put a string instead of a boolean.
import React from "react";
export interface ExampleClassProps {
string: string;
arrayOfStrings: { test: string };
boolean: boolean;
}
class ExampleClass extends React.PureComponent<ExampleClassProps> {
static defaultProps = {
string: "asd",
arrayOfStrings: { test: "asd" },
boolean: "true" //this should throw an error, since I'm assigning a string to type boolean
};
render() {
return <div>{this.props.string}</div>;
}
}
export default ExampleClass;
From my understanding Typescript should now throw an error saying, type string is not assignable to type boolean, but it doesn't.
I'm on Typescript 3.5.3 and I installed @types/react.
Also, writing a similar component as a functional component does actually work, so I only got the problem with classes:
import React from "react";
export interface ExampleFCProps {
stringProp?: string;
}
const ExampleFC: React.FC<ExampleFCProps> = ({ stringProp }) => {
return <div>{stringProp}</div>;
};
ExampleFC.defaultProps = { stringProp: 1 }; //this throws an error, since number is not type string
export default ExampleFC;