Reputation: 1327
So, I want one of my components to have an Interface passed to it. My approach was this
import { InterfaceType } from "typescript";
type Props = {
dataType: InterfaceType
}
export default function CreateRow(props: Props) {
return (
<div>"test"</div>
);
}
and the call to the component
<CreateRow dataType={ISchool}/>
But I get
'ISchool' only refers to a type, but is being used as a value here.
why is this happening and how can I fix it?
Edit: In CreateRow, I want to create objects of the type dataType which will come from the Props. The interface that will be passed through Props.dataType will be used in CreateRow to create objects of that type.
Upvotes: 0
Views: 195
Reputation: 187004
You need to rethink your approach here.
Props are runtime values. However, types exist only at compile time. This means you cannot pass a type as a prop.
That's what this error means:
'ISchool' only refers to a type, but is being used as a value here.
ISchool
is a type, and does not exist when the code is actually running. So passing as a prop can't work.
What you can do is make CreateRow
a generic function. This lets it be aware of a specific type, and enforce that you use that type in its props.
For example:
type Props<T> = {
rowData: T
}
export default function CreateRow<T>(props: Props<T>) {
return (
<div>"test"</div>
);
}
Which you might use like:
const testA = <CreateRow<AbcNum> rowData={{ abc: 123 }} /> // fine
const testB = <CreateRow<AbcNum> rowData={{ abc: 'asd' }} /> // type error
// or
const CreateAbcNumRow = CreateRow<AbcNum>
const testC = <CreateAbcNumRow rowData={{ abc: 123 }} /> // fine
Upvotes: 1