Reputation:
With Typescript in React, I wish to create a prop type that accepts a generic interface.
interface Waffle
{
startEating: number;
endEating: number;
...
}
interface Pancake
{
pourSyrup: boolean;
bake: boolean;
...
}
interface classProps
{
anInterface: ???;
}
class Food extends React.Component<classProps, null>
{ ... }
In the example, how do I type the 'anInterface' prop to be of type interface; that is, to accept an object of Waffle or an object of Pancake?
Upvotes: 2
Views: 417
Reputation: 33041
Take a look here:
type Props<D, S> = {
data: D;
selector: (data: D) => S;
};
const Comp = <D, S>(props: Props<D, S>) => null;
const result = (
<Comp<number, string>
data={2}
selector={(data: number) => "fg"}
/>
); // ok
const result2 = (
<Comp<number, string> // <--- here is the syntax for component with generic props
data={2}
// expected error
selector={(data: string) => "fg"}
/>
);
Example is take from my typescript blog
Upvotes: 0
Reputation: 1799
This should work:
interface Waffle {
startEating: number;
endEating: number;
}
interface Pancake {
pourSyrup: boolean;
bake: boolean;
}
interface classProps<T> {
anInterface: T;
}
class Food<T> extends React.Component<classProps<T>, null> {
...
}
Take into account that if the rendering depends on the type of interface that you are receiving and you don't know the type at compile-time, the generic won't work.
Upvotes: 1