如何解决如果将其用作子级,则将额外的接口属性添加到组件
我正在使用React(或任何其他类似的库)以JSX语法 使用TypeScript。对于jsxFactory
,我正在使用自己的工厂。
这是我想要的最简单的版本:
<Panel>
<Banner text="FREE OFFER" align="left" />
</Panel>
将align
放在required
内时,Banner
属性仅Panel
。
Banner
可以在Panel
之外使用,但是在这种情况下,使用align
属性会引发错误。
我希望它在编译时发生。
我已经尝试过this on typescriptlang playground。
declare global {
namespace JSX {
interface ElementChildrenAttribute { children: {}; }
}
}
interface BannerInterface {
title: string,text: string
}
class Banner<T extends BannerInterface = BannerInterface> {
constructor(props: T) {
//
}
}
interface AlignmentInterface extends BannerInterface {
align: string
}
interface PanelInterface {
adId: string,children: Banner<AlignmentInterface> // I'm trying to pass the AlignmentInterface to the Banner generic
}
class Panel {
constructor(props: PanelInterface) {
//
}
}
// I want this to throw compile error,as align is not in the BannerInterface
const adBanner = <Banner title="Independent Banner" text="test" align="left" />;
// I also want this to throw as Banner is being used as a children of Panel,// and for that I want the align prop to be required.
const panelBanner = (<Panel adId="1">
<Banner title="Banner inside Panel" text="test" />
</Panel>);
export default { Panel,Banner };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。