0

So, I want to create a component which will create some inputs, needed for creating an entity in the back-end.

For this, I have two ideas:

1st

Create a component which takes a type as a prop
Pass the type to the prop
Iterate over its keys
For each key, create an input

For this approach, my component looks like this:

import { Type } from "typescript";

type Props = {
    dataType: Type
}

export default function CreateRow(props: Props) {
  return (
    <div>//iteration over keys</div>
  );  
}

and the component would be called like this:

import type {EducatieItem} from './EducatieItem';

        <CreateRow dataType={EducatieItem}/>

but this doesn't work. I get

'EducatieItem' only refers to a type, but is being used as a value here.

EducatieItem is

export type EducatieItem = {
    id: string,
    name: string
};

The other idea was to create a generic component, like this:

export default function CreateRow<T>() {
  return (
    <div>//iteration over keys</div>
  );  
}

and the call:

        <CreateRow<EducatieItem>/>

this doesn't throw any error... yet.

If I actually try to iterate over the keys of T, then I will get the same error as before.

Is there any way to achieve what I want? Are any of my approaches valid though?

Thanks.

Octavian Niculescu
  • 1,177
  • 1
  • 3
  • 24
  • Does this answer your question? [How to check the object type on runtime in TypeScript?](https://stackoverflow.com/questions/44078205/how-to-check-the-object-type-on-runtime-in-typescript) – Etheryte Jun 17 '22 at 10:12
  • @Etheryte no, it doesn't, sorry – Octavian Niculescu Jun 17 '22 at 10:17
  • It does though? Types don't exist at runtime so you can't iterate over them at runtime. That's also what your error message is telling you, you can't use a type as a value. – Etheryte Jun 17 '22 at 11:06
  • "Is there any way to achieve what I want? Are any of my approaches valid though?" - it partially answers it, ruling out my first approach only. Would you mind showing me how would you achieve what I proposed, please? – Octavian Niculescu Jun 17 '22 at 11:08
  • Your second approach is the same as the first one, just in a different syntactic way. You can't iterate over data that's not there. This isn't possible out of the box with Typescript. You can see further discussion under [this ticket](https://github.com/microsoft/TypeScript/issues/3628) with some proposals on how to sidestep the issue. – Etheryte Jun 17 '22 at 11:14
  • @Etheryte I see. What would your approach be in my situation though? Would you just send the input fields' name as an array, for example? – Octavian Niculescu Jun 17 '22 at 11:17

0 Answers0