Similarly to the previous response, there is room for refactoring to enhance clarity. It is important to specify the expected behavior in cases where withoutActions
is set to false
rather than true
or undefined
. For the sake of this explanation, it is assumed that both false
and undefined
yield the same behavior. If false
is not a valid option, you can easily replace withoutActions?: false
with withoutActions: undefined
as suggested in the earlier answer.
type Props = {
label: string;
children?: React.ReactNode;
corporate: Corporate;
} & (
{
withoutActions: true;
} |
{
withoutActions?: false;
fieldKey: KeyProperties;
}
)
However, it is crucial to be mindful of a potential pitfall in this approach. Due to TypeScript's structural typing, excess property checking only occurs when directly assigning an object literal. Excess property checking is not triggered when assigning an object and inferring its type. While TypeScript and React treat direct props declarations as object literals and perform the desired excess property checking, there are scenarios where assigning objects to variables with inferred types might not raise warnings about excess properties.
Take a look at this demo based on your original example. Example #1 and #2 showcase errors due to excess property checking, while example #3 does not.
const ExampleOne = () => {
// Type error - excess property checking
return <Component label={''} corporate={''} withoutActions fieldKey={''} />;
}
const ExampleTwo = () => {
const props: Props = {
label: '',
corporate: '',
withoutActions: true,
// Type error - excess property checking
fieldKey: '',
}
return <Component {...props} />;
}
const ExampleThree = () => {
const props = {
label: '',
corporate: '',
withoutActions: true,
fieldKey: '',
}
// No type error - no excess property checking
return <Component {...props} />;
}