我有一个像这样的 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/