#Polymorphic React component type error

19 messages · Page 1 of 1 (latest)

undone mulch
#

I need to get rid of the type error with the Component variable

tall fernBOT
#
alii_dev#0

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>)
...```

rancid pollen
# tall fern

const Component = as as keyof Elements;
This assertion works, don't know why tho, because it doesn't change the type in any way

undone mulch
rancid pollen
#

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

undone mulch
tall fernBOT
#
alii_dev#0

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>)
...```

rancid pollen
undone mulch
#

Typescript will automatically pick the right attributes based on as, see the examples in the playgrounds

rancid pollen
#

Right, but now that href property is not going anywhere
I mean it's not being used in the CTAButton component

drowsy plover
#

I have never coded before don’t ask me 💀

snow patio
#

@drowsy plover Please don't post into help channels just to say you don't know.

drowsy plover
#

Ok

#

Sorry

undone mulch
#
// 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>;
rancid pollen
#

@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