如何确保只能将特定类型的ReactElement传递给打字稿中的Component道具

时间:2020-02-07 06:32:24

标签: reactjs typescript

eslint和vscode在传递不兼容的ReactElement类型时不会显示任何验证错误。我在任何文档或示例中都找不到如何验证这一点的方法。

// Footer.tsx

export interface FooterProps {
    /**
     * footer primary button text
     */
    primaryButtonText: string;

}

class Footer extends PureComponent<FooterProps> {
  // render Footer here
}

// Modal.tsx

interface ModalProps {
  footer: ReactElement<FooterProps>;
}


class Modal extends PureComponent<ModalProps>{
   //render modal here
}


// Text.tsx

interface TextProps{
  color: string;
}

class Text extends PureComponent<TextProps>{
   //render Text
}

App.tsx

<Modal footer={<Footer primaryButtonText="hello world" />}  // This expected to work since footer receives the correct type and it works.

<Modal footer={<Text title="hello world" />} // expected to fail as footer receives incorrect type, but there is no any validation error, in fact doesn't matter which element you pass no error will occur.

版本:

"typescript": "^3.7.2"
"eslint-plugin-react": "^7.16.0",
"eslint": "^6.7.0",

1 个答案:

答案 0 :(得分:0)

您可以通过将ModalProps限制为:

interface ModalProps {
  footer: Text<FooterProps> | Footer<FooterProps>;
}

在上面的书面代码中。如果footerTextFooter之外还有其他东西,打字稿应该提出投诉。