You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The implementation is just a contrived example, but the point is that the click event handler needs to use the generic HTMLElement, since it can't be known at compile-time if it's going to be a HTMLButtonElement or a HTMLDivElement – therefore a common super class is used.
The problem is that a consumer can assume a potentially problematic specific type when providing an event handler:
functiononButtonClick(event: MouseEvent<HTMLButtonElement>){event.currentTarget.disabled;// Only exists on `HTMLButtonElement`, not on `HTMLDivElement`}// Ok with covariancereturn<ButtononClick={onButtonClick}/>;
With covariance this is allowed and potentially problematic. By using the property syntax, the above assignment to onClick will be an error and you'd have to accept an HTMLElement in the event. However you can still refine it with instanceof:
These are not equivalent:
We might want to consider the second syntax to disallow covariance.
This example helped me understand the situation:
The implementation is just a contrived example, but the point is that the click event handler needs to use the generic
HTMLElement
, since it can't be known at compile-time if it's going to be aHTMLButtonElement
or aHTMLDivElement
– therefore a common super class is used.The problem is that a consumer can assume a potentially problematic specific type when providing an event handler:
With covariance this is allowed and potentially problematic. By using the property syntax, the above assignment to
onClick
will be an error and you'd have to accept anHTMLElement
in the event. However you can still refine it withinstanceof
:Personally, I like the method syntax and I think it's a bit closer to the function declaration syntax that we use, that's why I picked it originally. But TypeScript doesn't seem to support a compiler option that opts-out of bivariance for the method syntax.
See also: Wikipedia on covariance and contravariance
The text was updated successfully, but these errors were encountered: