Typing component based on props
Hi all,
I'm trying to type a Link component based on it's props. If
url
is passed as a prop, I want the type of the component to be an HTMLAnchor
element, if I pass in an onClick
I want it to be an HTMLButton
etc.
I have the following but it doesn't seem to work. It lets me pass in both an onClick and an href, which shouldn't be possible as href doesn't exist on HTMLButton
https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOAGWADsBrAFRQHMAeAVTiQAeMJIwAmAZzjiYUJhzgAfOAFcxSTEySiANHADy-ISIlwAFKYCUcALwA+OADcIwUVaWrR6zaPvW4Ab1IASGUoABsAfgAuOB4AbmCIRgBhMOA0Zmj9BKC0ZWlcAAUcMBjpWUYOBIBfBIpqWgYWdg5iiDBxXkNhMUlyuUUVNQ1GLV0DQR6Tcys7R2dXQY8vUZ8beiY2Tl5x+wAyYNM+SeM+mTlgoIjEYhgAOgAJVgBZOjaOrifXgEFGNAALaAAUTCSBAIhgtkuMQmRl6Zlm9icLku12Q6HuXzeJU6WIAQsoYDAkiCwRCoUEgjF0RhHi9se1cfSAMpgFCMUngxiQix1QSQWBwTCqDDAJIbZrbY5wkz9SpLYbecbdU5mSw2JELNxDTwjLS2UxgHExJpbVo4nb6WxWQJBIgwUKMOBcFC2LgAeldNXIXFNLTgeQKIHe1nwYQgYXwcCSqXSzGs-nVc381WqcH+REwofDkbg7tscSAATS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
5 Replies
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Awesome, thank you
Although now I think it would be valid to have both an onclick and url, as anchor tags can have click handlers. should be an easy change. cheers 🙂
Hmm, how would I write a typeguard for this type?
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Yeah, so I can pass spread the props in a, button, and span tag without ts complaining
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View