#Inject type-safe props into dynamically imported components

2 messages · Page 1 of 1 (latest)

main finch
#

Hi all!
I am needing some assistance. I have an object type as follows:

{
  component: AstroComponentFactory;
  props: {
    [x: string]: any;
  }
}

And I am rendering the component like this:

---
// ...
const obj = getDynamicComponent();
---

<obj.component {...obj.props} />

This code works, but I don't get type safety when writing my component:

---
const { greeting } = Astro.props; // `greeting` is type any
---

<p>{greeting}, world!</p>

The component also has a custom exported constant object. I want to be able to hopefully read this object and transform a type from it that is used as props. Basically I want to inject type-safe props into my components based off of extraData. Let me show you an example:

---
export const extraData = [{
  type: "text",
  name: "greeting", // I want to pull the value `greeting` and use this as the key in props below
  defaultValue: "Hello",
}];

const { greeting } = Astro.props; // `greeting` here is a type safe string, if the name above is renamed, this fails the ts checker
---

I have no idea how to do this, or if this is possible. I'm guessing this might be possible with an integration? Any assistance is greatly appreciated!

cloud finch
#

You will typically type the Props, like so:

type Props = {
    greeting: string
}
const { greeting } = Astro.props;

When you fetch a collection entry, you normally get the correct type automatically, but if you want to pass that entry to a component, Astro has the CollectionEntry<"blog"> type:

type Props = {
    blog: CollectionEntry<"blog">
}
const { blog } = Astro.props;

where blog will be typed.
You might want to look at how that's implemented and do something similar to dynamically set the type.