TypeScript + React: Properly Defining Default Parameters

Say that you define your component as follows:

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>
    );
  }
}

when you want to use it, TypeScript wants defaultedprop from you , although it is defined in defaultProps:

<Comp req="something" />  // ERROR: TypeScript: prop 'defaulted' is required

However, if you define the props interface as follows:

interface IProps {
  req: string;
  defaulted?: string;  // note the ? here
}

then you cannot use it in:

render() {
  const { defaulted } = this.props;  // ERROR: prop 'defaulted' possibly undefined

  return (
    <span>{defaulted.toUpperCase()}</span>
  );
}

How to define IProps, defaultProps and component correctly so that types make sense?

EDIT:

I use the flag strictNullChecks.

+4
source share
2 answers

I have an example with the following code (ComponentBase is just my wrapper around React.Component).

: "strictNullChecks"

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>
        );
    }
}

Visual Studio, TypeScript 2.0.3, TSLint 0.5.39.

+3

<span>{(defaulted as string).toUpperCase()}</span>

. Foo barProp, Parent defaultProps, Parent render

<Foo barProp={this.props.barProp as string} />
0

Source: https://habr.com/ru/post/1657286/


All Articles