简体   繁体   English

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

[英]How to descturcture an object in Typescript when properties are optional?

I have a generic component which has some optional properties, I need to destructure props but I get errors我有一个具有一些可选属性的通用组件,我需要解构 props 但出现错误

    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;

How can I destructure those optional properties without getting Typescript error?如何在不出现 Typescript 错误的情况下解构这些可选属性?

在此处输入图片说明

Because the Page component uses the renderOverlayContent prop regardless and the prop isn't presented in the IStepStateWithDispatch or ITaskStateWithDispatch type (that's the reason of the error), I can make a assumption that you want the Page component to require all the props of the interfaces IStepStateWithDispatch , IScenarioPageProps and ITaskStateWithDispatch .因为Page组件renderOverlayContent都使用renderOverlayContent道具,并且该道具没有出现在IStepStateWithDispatchITaskStateWithDispatch类型中(这就是错误的原因),我可以假设您希望Page组件需要接口的所有道具IStepStateWithDispatchIScenarioPagePropsITaskStateWithDispatch

If my assumption is correct, then you need to replace |如果我的假设是正确的,那么你需要替换| with & in the props type declaration.在 props 类型声明中使用& It will tell TypeScript that the props object has the properties from all the interfaces.它会告诉 TypeScript props对象具有来自所有接口的属性。

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

If my assumption is not correct (the component is polymorphic), then you need to check that the renderOverlayContent prop is given and then use it:如果我的假设不正确(组件是多态的),那么您需要检查renderOverlayContent是否已给出,然后使用它:

// ...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM