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?
undefined(TS types are not sealed, objects can always have props TS doesn't know about. The valueconst x = { hidingTimeoutMs: 0, displayingClass: "", hidingClass: "", displayingInlineStyle: 1}is a perfectly validAnimationContainerProps.) For example, as shown here using a utility type to automatically transform a union to an exclusive version. Does that fully address the question? If so I'll write up an answer explaining; if not, what am I missing?