reactjs - 如何使用 TypeScript 编写包含对象的 props 接口(interface)并与 defaultProps 合并

标签 reactjs typescript

我有一个像这样的 TypeScript props 接口(interface):

interface Props {
  children: ReactNode;
  components?: object;
  mode: string;
  actions: {
    copy: boolean;
    code: boolean;
    refresh: boolean;
    source: boolean;
  };
  source?: string;
  readonly withStyles?: object;
  styles?: object;
}

我有一个相应的 defaultProps 接口(interface):

class Box extends Component<Props, State> {
  public static defaultProps = {
    mode: 'full',
    actions: {
      copy: true,
      code: true,
      refresh: true,
      source: true,
    },
  };

  ....

}

用户应该只能指定一部分 actions在一个组件上,其余部分应从 defaultProps 合并.

例如,如果用户指定:

<Box actions={{ copy: false }} />

我希望 defaultProps 能够填补空白以生成 props.actions作为{ copy: false, code: true, refresh: true, source: true } .

但是,我目前收到 TypeScript 错误:Type '{ copy: boolean; }' is missing the following properties from type '{ copy: boolean; code: boolean; refresh: boolean; source: boolean; }': code, refresh, source .

我怎样才能让它正常工作?

TypeScript v.3.2.2
@types/react v16.8.2

最佳答案

React 没有深入的 defaultProps 检查/合并,TypeScript 不会改变这一点。

处理这个问题的一种方法是制作包装器组件:

//pure js

const defaultActions = {
  copy: true,
  paste: false
};

const Box = props => JSON.stringify(props);
const BoxWithDefaultActions = ({ actions, ...rest }) => (
  <Box actions={{ ...defaultActions, ...actions }} {...rest} />
);

const App = () => (
  <>
      <Box actions={{ copy: false }} />
      <BoxWithDefaultActions actions={{ copy: false }} />
  </>
);

/**
Box:
  { "actions": { "copy": false } }
Box with actions:
  { "actions": { "copy": false, "paste": false } }
**/

//HOC or render props component could be even better "solution". 

您可以在 React Github 问题:https://github.com/facebook/react/issues/2568

关于reactjs - 如何使用 TypeScript 编写包含对象的 props 接口(interface)并与 defaultProps 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54879243/

相关文章:

angular - TS2532 : Object is possibly 'undefined'

javascript - 如果 JSON 字段不存在,则 JSX 跳过

javascript - 错误 : Target container is not a DOM element. - 使用开箱即用的应用程序

javascript - React.js : how separate jsx es6

reactjs - Typescript 类型检查的通用 Prop

node.js - 如何在 VS Code 中调试 React Tape 单元测试

typescript - 如何从 lib.dom.d.ts 导入接口(interface)?

javascript - 错误 TS2339 : Property 'Default' does not exist on type 'string' . **

Typescript:TextNode 的类型

javascript - 如何使用顶级等待将 TypeScript 编译为 JavaScript?