简体   繁体   English

有没有办法在使用之前将类型传递给通用组件?

[英]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.我需要在最终用户使用它之前以某种方式将类型传递给 ComponentsOverrideContextProvider。 Is there any way?有什么办法吗?

user should not be doing like this <ConcreteProvider<Type>></ConcreateProvider> it should be typed before he calls this component用户不应该这样做<ConcreteProvider<Type>></ConcreateProvider>它应该在他调用这个组件之前输入

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 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM