developit / developit/unistore

Better typings for `connect`

Open
#160 2 comments 3 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
2.8k
Forks
134
PR merge metrics
No merged PRs in 30d

Description

Hey,
using the current `connect` in typescript seems to give not as much type safety as possible. I came ob with these types/changes to make it more safe for us, as we had it more than once that we actually broke things without these types.

```javascript
export const safeConnect = (
pickFromState: (keyof K) & (keyof I) & string | Array<(keyof K) & (keyof I) & string> | StateMapper,
actions?: PropsActions | Array> | SafeActionCreator,
): ((Child: ComponentConstructor | AnyComponent) => ComponentConstructor) =>
connect(
pickFromState,
Array.isArray(actions) ? actions.reduce((prev, current) => ({ ...prev, ...current }), {}) : actions,
);

export type SafeActionCreator = (store: Store) => PropsActions;

type PropsActions, K> = {
[P in keyof Partial]: I[P] extends ((...args: any[]) => void)
? (s: State, ...a: Parameters) => Promise> | Partial | void
: never
};
```

This ensures a few things, maybe an example shows that better:

```javascript
export interface Store {
counter: number,
}

export const counterAction = {
setCounter: (_: State, n: number) => ({ counter: n }),
};

export interface ComponentConnectedProps {
counter: number;
setCounter: (count: number) => void
}

// usage
export const ConnectedComponent = safeConnect<{}, {}, Store, ComponentConnectedProps>(
['counter'], // or 'counter'
[counterAction], // or counterAction
)(Component);
```

1. `pickFromState` parameter from `safeConnect`
* needs to be a key of the `Store` and the `ComponentConnectedProps`
2. `actions` parameter from `safeConnect`
* key of the action object needs to be in the `ComponentConnectedProps`
* function parameter (without the `State`) needs to match the one in `ComponentConnectedProps`
* return type of the action function needs to be `Partial` of the state

The one thing it can not ensure, is that **all** of the items from `ComponentConnectedProps` are there.

Is there interest to get some version of this upstream?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.