Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6208

Make TypeScript function accept Redux connected component

$
0
0

I've got a React Native project where I've got a Screen class, and HomeScreen, MyProfileScreen classes derived from it (I know, composition preferred over inheritance, but let's keep that argument somewhere else) (irrelevant parts redacted, but notice the identifier getter function, I'll come to that):

export default class Screen<P = {},S = {},SS = {}> extends Component<P,S,SS> {
    static get identifier(){
        return this.name;
    }     
}

Then, in my home screen and profile screen (which basically has the same structure with home screen):

export default class HomeScreen extends Screen<HomeScreenProps & HomeScreenDispatchProps>{
    [...]
}

Now, I'm writing a function where it accepts a class derived from Screen, and accessing its static getter identifier:

export default function wrapStackNavigator<T extends typeof Screen>(screen:T){
    return <Stack.Navigator>
        <Stack.Screen name={screen.identifier} component={screen}/>
    </Stack.Navigator>
}

So far so good, I can call wrapStackNavigator with any screen classes with no type errors. Now the problem begins. I want to make my screens connected components, so I go ahead and connect them to Redux as usual:

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(HomeScreen)

At this point, calls wrapStackNavigator starts complaining about types not being compatible. I know the reason: connect returns a different type which wraps the original class, but I have no idea how to fix it. I've tried to change wrapStackNavigator to accept ConnectedComponent or InferableComponentEnhancerWithProps (which apparently connect returns) but no avail (or I've got the type arguments wrong).

How can I make wrapStackNavigator accept either a class derived from Screen, or a connected class derived from Screen, while still being able to access static properties of the passed derived Screen class, with no typing errors? (and please, no casting to any, I know that would "solve" it but I don't consider it a solution). I'm on TypeScript 3.6.3.


Viewing all articles
Browse latest Browse all 6208

Trending Articles