I have a React application (although the question is not really about React), with typescript.
In a functional component (whose consumer I want to be able to pass OR styles OR a class, but not both), I use the following props type:
type AnimationContainerProps = { hidingTimeoutMs: number } & (
| {
displayingClass: string;
hidingClass: string;
}
| {
displayingInlineStyle: string;
hidingInlineStyle: string;
}
);
I would like to destructure it in a single instruction, like:
const { hidingTimeoutMs, displayingClass, hidingClass, displayingInlineStyle, hidingInlineStyle } = props
In javascript, it would be no problem and I would receive undefined in the non-existent props. But in Typescript, I can't do this, because I'll get a Property 'XXX' does not exist on type 'AnimationContainerProps'.ts(2339).
I want to avoid making the attributions one by one. Do you guys think of a way to destructure it?
Here's one way you could do it:
For the missing properties, you can use
undefinedor any other value or object that's convenient.In a comment, jcalz points out that your definition of the AnimationContainerProps type is not properly exclusive. For example, someone could pass
stringvalues for all four class/style props to your component. Or they could pass the following object, which hasdisplayingInlineStyleandhidingInlineStylevalues of the wrong type:If you're concerned about this case, you can change your type and force missing/undefined values for
displayingInlineStyleandhidingInlineStyleifdisplayingClassandhidingClassare specified, and vice versa:With this change, your original destructuring code would work as desired.