属性是可选的时,如何在Typescript中解构对象?

时间:2019-06-28 00:57:31

标签: javascript reactjs typescript

我有一个通用组件,该组件具有一些可选属性,我需要分解道具,但会出错

    interface IScenarioPageProps extends IScenarioStateWithDispatch {
    isOverlayVisible?: boolean;
    renderOverlayContent?: () => void;
}

const Page = (props: IStepStateWithDispatch | IScenarioPageProps | ITaskStateWithDispatch) => {
    const { taskState, stepState, isOverlayVisible, renderOverlayContent } = props;
    const { selectedTaskId, selectedTask } = taskState;
    const { selectedStepId, selectedStep } = stepState;

    const style = StyleSheet.create({
        content: {
            'background-color': getTheme().palette.white,
            height: '100vh'
        }
    });

    return (
        <div className={css(style.content)}>
            {isOverlayVisible && <Modal>{renderOverlayContent()}</Modal>}
        </div>
    );
};

export default Page;

如何在不出现Typescript错误的情况下解构这些可选属性?

enter image description here

1 个答案:

答案 0 :(得分:1)

由于Page组件使用renderOverlayContent道具,并且道具没有以IStepStateWithDispatchITaskStateWithDispatch类型显示(这就是错误的原因),我可以假设您希望Page组件需要所有接口IStepStateWithDispatchIScenarioPagePropsITaskStateWithDispatch的道具。

如果我的假设正确,那么您需要在props类型声明中将|替换为&。它将告诉TypeScript props对象具有所有接口的属性。

const Page = (props: IStepStateWithDispatch & IScenarioPageProps & ITaskStateWithDispatch) => {
    // ...
}

如果我的假设不正确(该组件是多态的),则需要检查是否提供了renderOverlayContent道具,然后使用它:

// ...

// const {renderOverlayContent} = props; // Remove this

return (
    <div className={css(style.content)}>
        {isOverlayVisible &&
            <Modal>
                {'renderOverlayContent' in props && props.renderOverlayContent && props.renderOverlayContent()}
            </Modal>
        }
    </div>
);