howard wolowitz
howard wolowitz

Reputation: 628

Is there a way to pass type to generic component before using it?

export const ComponentsOverrideContextProvider= <M extends Record<any, any>>({children, components}: {children: React.ReactNode, components: M}) => {
return <ComponentOverrideContext.Provider value={{ ...components }}>{children}</ComponentOverrideContext.Provider>;} 

i have a component above which is generic and it should not be tight to a specific implementation, or order to avoid it i am doing something like

// concrete implementation

export const ConcreteProvider = ComponentsOverrideContextProvider;

and I need to somehow pass type to ComponentsOverrideContextProvider before end user uses it. Is there any way ?

user should not be doing like this <ConcreteProvider<Type>></ConcreateProvider> it should be typed before he calls this component

Upvotes: 1

Views: 45

Answers (1)

ghybs
ghybs

Reputation: 53185

Simply specify the concrete type when doing your concrete implementation:

export const ConcreteProvider =
    ComponentsOverrideContextProvider<
        // Pass the concrete type
        Record<string, number>
    >;

() => (
    <ConcreteProvider components={{
        foo: 0,
        bar: "hello" // Error: Type 'string' is not assignable to type 'number'.
    //  ~~~
    }}>
        Some children
    </ConcreteProvider>
)

Playground Link

Upvotes: 1

Related Questions