Reputation: 183
it is example code. How to pass type global
in function passed how to children of Cell component?
import * as React from "react";
const Context = React.createContext<any>(null);
function Cell(props: { children: (data: any) => string }) {
const data = React.useContext(Context);
return <div>{props.children(data.data)}</div>;
}
interface PropsRoot<T> {
children: JSX.Element | JSX.Element[];
global: T;
}
function Root<T>(props: PropsRoot<T>) {
return (
<div>
<Context.Provider value={{ data: props.global }}>
{props.children}
</Context.Provider>
</div>
);
}
export default function App() {
return (
<Root global="asdf">
{/* data in function should have type that pass in component Root property global */}
<Cell>{(data) => data}</Cell>
<Cell>{(data) => data}</Cell>
</Root>
);
}
See online here. It is imperative to use a generic, because so many options can be passed in the property global.
Upvotes: 4
Views: 3728
Reputation: 3639
It's allowed to make generic components:
function Cell<T>(props: {
children: (data: T) => string
}) { /* ... */ }
UPD: for quite a while already TS supports using generics in JSX, so you can do <Cell<YourType> />
. However in vast majority of cases you don't need this syntax, if you find yourself needing it, you may want to reconsider your component architecture. But if you're sure you need it, it's alright.
But for this to work, you need to provide a way for Typescript to somehow infer, what the T
type argument is, because you can't write <Cell<YourType> />
in JSX. For example, the type would be inferred if you specify type for data
when you pass it as a parameter of a function, that is a child of Cell
.
In this particular case, it's hard to make up anything sensible. Do you know exactly, what type will be inside your context? If yes, just create context like createContext<YourType>(...)
and you don't really need generics anymore, useContext
will infer the context type and you can just define the children prop to be a function that accepts YourType
.
If you don't know this type, then I don't really see, what you want, because context contains any
, so how do you want TS to infer something better than any
for functions that use this context?
Upvotes: 2