TypeScript + React:正确定义defaultProps

Ide*_*ixx 6 javascript typescript reactjs

假设您像这样定义组件:

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

当你想使用它时,TypeScript需要defaulted你的道具,即使它在以下定义defaultProps:

<Comp req="something" />  // ERROR: TypeScript: prop 'defaulted' is required
Run Code Online (Sandbox Code Playgroud)

但是,如果你像这样定义道具界面:

interface IProps {
  req: string;
  defaulted?: string;  // note the ? here
}
Run Code Online (Sandbox Code Playgroud)

然后你不能用它:

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

  return (
    <span>{defaulted.toUpperCase()}</span>
  );
}
Run Code Online (Sandbox Code Playgroud)

如何正确定义IProps,defaultProps和组件以使类型有意义?

编辑:

我正在使用strictNullChecks旗帜.

Bjö*_*art 4

我有一个包含以下代码的示例(ComponentBase 只是我对 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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用 Visual Studio Code、TypeScript 2.0.3、TSLint 0.5.39 没有任何问题。