[英]How to TypeScript a props interface containing an object and merge with defaultProps
我有一个类似这样的TypeScript道具界面:
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接口:
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
Type '{ copy: boolean; }' is missing the following properties from type '{ copy: boolean; code: boolean; refresh: boolean; source: boolean; }': code, refresh, source
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.