Reactjs 在React with TypeScript中键入默认的直通道具

Reactjs 在React with TypeScript中键入默认的直通道具,reactjs,typescript,typescript3.0,Reactjs,Typescript,Typescript3.0,React组件接受并通过一些道具传递给孩子是很常见的。如果由于孩子的defaultProps指定,孩子身上的一个或多个道具是可选的,那么如何为正确接受自己和孩子道具的父母定义类型或接口 考虑以下示例: interface ParagraphProps { body: string, imgSrc: string, } interface SectionProps extends ParagraphProps { title: string, } class Paragraph e

React组件接受并通过一些道具传递给孩子是很常见的。如果由于孩子的
defaultProps
指定,孩子身上的一个或多个道具是可选的,那么如何为正确接受自己和孩子道具的父母定义
类型
接口

考虑以下示例:

interface ParagraphProps {
  body: string,
  imgSrc: string,
}

interface SectionProps extends ParagraphProps {
  title: string,
}

class Paragraph extends React.Component<ParagraphProps> {
  static defaultProps = {
    imgSrc: '../images/section-break.jpg',
  };

  render() {
    const { body, imgSrc } = this.props;

    return (
      <p>{body}</p>
      {!!imgSrc && <img src={imgSrc}>}
    );
  }
}

class Section extends React.Component<SectionProps> {
  render() {
    const { title, ...rest } = this.props;

    return (
      <section>
        <h1>{title}</h1>
        <Paragraph {...rest}>
      </section>
    );
  }
}
然后我们发现现在
title
body
是可选的,这不是我们想要的


在保持干燥的同时,我应该如何指定
部分
的道具,以规定
标题
正文
是必需的,而
imgSrc
是可选的?

由于
段落道具
界面对应于
段落
组件,保持这些“对齐”可能是有意义的. 您知道,
imgSrc
有一个默认值,因此在界面中将其标记为可选是有意义的,因为使用
段落
组件的人(不仅是
部分
组件)都不需要传入
imgSrc

接口段落道具{
正文:字符串,
imgSrc?:字符串,
}
如果
段落
组件的所有用户都不需要传入
imgSrc
(而不是
部分
组件),那么将该默认值移动到
部分
组件可能更有意义

最后,如果您想使其更具动态性,可以执行以下操作,尽管在本例中可能比必要的更复杂

//仅当不是3.5+时才需要(https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-省略辅助对象类型)
类型省略=拾取;
界面段落道具{
正文:字符串;
imgSrc:字符串;
}
类型PropsWithDefaults=段落类型的keyof.defaultProps;
类型TransformedProps=部分&
省略
接口SectionProps扩展了TransformedProps{
标题:字符串;
}
类节扩展了React.Component{
render(){
const{title,…rest}=this.props;
回来
}
}
类。组件{
静态defaultProps={
imgSrc:“../images/section break.jpg”
};
render(){
返回null;
}
}
这里,
TransformedProps
类型包括
ParagraphProps
中的所有道具,其中
段落中的道具。defaultProps
通过使用
部分
成为可选道具。有关如何形成此结构的更多详细信息,请参见

interface SectionProps {
  title: string,
}

type FullSectionProps = Partial<SectionProps & PartialProps>;