Say you define your component like so:
interface IProps {
req: string;
defaulted: string;
}
class Comp extends React.Component<IProps, void> {
static defaultProps = {
defaulted: 'test',
};
render() {
const { defaulted } = this.props;
return (
<span>{defaulted.toUpperCase()}</span>
);
}
}
defaulted
defaultProps
<Comp req="something" /> // ERROR: TypeScript: prop 'defaulted' is required
interface IProps {
req: string;
defaulted?: string; // note the ? here
}
render() {
const { defaulted } = this.props; // ERROR: prop 'defaulted' possibly undefined
return (
<span>{defaulted.toUpperCase()}</span>
);
}
strictNullChecks
I have an example with the following code (ComponentBase is just my wrapper around React.Component).
Edit: updated code to work with 'strictNullChecks' setting
interface IExampleProps {
name: string;
otherPerson?: string;
}
/**
* Class with props with default values
*
* @class Example
* @extends {ComponentBase<IComponentBaseSubProps, {}>}
*/
export class Example extends ComponentBase<IExampleProps, {}> {
public static defaultProps: IExampleProps = {
otherPerson: "Simon",
name: "Johnny"
};
constructor(props: IExampleProps) {
super(props);
}
public render(): JSX.Element {
const person: string = this.props.otherPerson === undefined ? "" : this.props.otherPerson;
return(
<div>
<h1><small>Message by ComponentBaseSub: Hello {this.props.name} and {person} </small></h1>
</div>
);
}
}
I have no issues using Visual Studio Code, TypeScript 2.0.3, TSLint 0.5.39.