#Polymorphic React component type error
19 messages · Page 1 of 1 (latest)
Preview:```ts
import * as React from "react"
type Elements = Pick<
JSX.IntrinsicElements,
"a" | "button"
type CTAButtonProps<T extends keyof Elements> = {
as: T
children: React.ReactNode
} & (T extends "a"
? React.AnchorHTMLAttributes<HTMLElement>
: React.ButtonHTMLAttributes<HTMLElement>)
...```
const Component = as as keyof Elements;
This assertion works, don't know why tho, because it doesn't change the type in any way
I tried it too but it doesn't work!!
Oh, it doesn't work in the playground
It worked when I tried locally tho...
(It works on my machine.jpg)
Dont know, someone else could help
solved! I have to remove rest
Preview:```ts
import * as React from "react"
type Elements = Pick<
JSX.IntrinsicElements,
"a" | "button"
type CTAButtonProps<T extends keyof Elements> = {
as: T
children: React.ReactNode
} & (T extends "a"
? React.AnchorHTMLAttributes<HTMLElement>
: React.ButtonHTMLAttributes<HTMLElement>)
...```
Wouldn't you need to forward those other props?
Typescript will automatically pick the right attributes based on as, see the examples in the playgrounds
Right, but now that href property is not going anywhere
I mean it's not being used in the CTAButton component
I have never coded before don’t ask me 💀
@drowsy plover Please don't post into help channels just to say you don't know.
// expected error cus it returns <button>...<button>
const a = <CTAButton as="button" href="..." type="button">hi</CTAButton>;
// it returns anchor tag <a>...</a>
const b= <CTAButton as="a" href="...">hi</CTAButton>;
@undone mulch
With regard to types, your code is fine now
But if you render the component as <CTAButton as="a" href="...">hi</CTAButton>
On your browser UI that link would actually have no href
<Component
className="..."
>
Becuase it is not being forwarded into here
Functionally it's broken