I was asking this question with a more complex version of this basic concept
Rel: Can Generic JSX.Elements work in Typescript
I narrowed it down to the core Elements:
This is Object A
that takes parameters from TypeA
type TypeA = {
label: string
value: number
}
const ObjA = ({ label, value }:TypeA) => {
return <div>
<div>Label: {label}</div>
<div>Value: {value}</div>
</div>
}
This is Object B
that takes parameters from TypeB
type TypeB = {
label: string
value: string
bool: boolean
}
const ObjB = ({ label, value, bool }:TypeB) => {
return <div>
<div>Label: {label}</div>
{bool && <div>Value: {value}</div>}
</div>
}
Now I collect this ComponentGroup inside an array and create a Type out of this Array:
const ComponentCollection = [
ObjA,
ObjB
] as const
type Components = typeof ComponentCollection[number]
Then I create a generic component:
interface GenericProps<T extends Components> {
Component: T
title: string
}
const Generic = <T extends Components,>({ Component, title, ...props }:GenericProps<T>) => {
return (
<div>
<label>{title}</label>
<Component {...props}/>
</div>
)
}
At last I can call the generic component as follows:
<Generic Component={ObjA} title={'Usage A'} label={'Object A'} value={'String A'}/>
<Generic Component={ObjB} title={'Usage B no Bool'} label={'Object B'} value={0}/>
<Generic Component={ObjB} title={'Usage B with Bool'} label={'Object B'} value={0} bool/>
Altough it works really well in JavaScript, I messed something up with the typing.
I setup one TS-Playground and one Codepen:
TS-Playground: https://tsplay.dev/WvVarW
Codepen: https://codepen.io/Cascade8/pen/eYezGVV
Goal:
- Convert this code above in correct TypeScript code
- Compile without any TS-Errors or
/@ts-ignore
- Make IntelliSense work, so if you type
<Generic Component={ObjA} ...
it shows the available type attributes for this Object. In this case:label={string: } value={string: }
What i don't want:
- Usage of classes or the old function syntax as our EsLint requires us to use an Arrow-Function if possible.
- Passing the Objects as a Child.
I know this works, but it is not the prefered solution as the main Project has a lot of groups like this that get rendered like this.
And why shouldn't something work in TypeScript that works very simple in JavaScript.