【问题标题】:how scale dependent props in react with typescript?how scale dependent props in react with typescript?
【发布时间】:2022-12-02 05:50:03
【问题描述】:
The problem is based on the dependency of properties, where I have a property that depends on another property, but without both the component should continue to work.
In the code example below I have a component that has the inviteLabel prop and the onClickInvite prop. These properties are not required, but if I add one, I must add the other.
so does contactLabel and onClickContact.
import React from "react";
type Props = {
fullName: string;
onClickInvite?: () => void;
inviteLabel?: string;
onClickContact?: () => void;
contactLabel?: string;
};
const CardWithUserDetails = (props: Props) => {
return <div>test</div>;
};
function DebugWhileDeveloping() {
return <CardWithUserDetails fullName="test name" />;
}
How can I create a type that can make this dependency work? and how to scale the solution if you have to add more properties?
【问题讨论】:
标签:
reactjs
typescript
types
【解决方案1】:
You can create a type guard to check for the conditional existence of required properties:
type Props = {
fullName: string;
onClickInvite?: () => void;
inviteLabel?: string;
onClickContact?: () => void;
contactLabel?: string;
};
function hasInviteLabel(props: Props): props is Required<Props> {
return !!props.inviteLabel;
}
function hasContactLabel(props: Props): props is Required<Props> {
return !!props.contactLabel;
}
const CardWithUserDetails = (props: Props) => {
if (hasInviteLabel(props) && !props.onClickInvite) {
throw new Error("You must provide an onClickInvite prop if you provide an inviteLabel prop");
}
if (hasContactLabel(props) && !props.onClickContact) {
throw new Error("You must provide an onClickContact prop if you provide a contactLabel prop");
}
return <div>test</div>;
};
function DebugWhileDeveloping() {
return <CardWithUserDetails fullName="test name" />;
}
This type guard ensures that both props are present when either one is provided, and throws an error if a prop is missing. This approach can be scaled to any number of props.