fix type of selectors w/ subduxes

This commit is contained in:
Yanick Champoux 2023-09-20 10:41:34 -04:00
parent a6b6a54c72
commit e4083645bc
2 changed files with 21 additions and 11 deletions

View File

@ -5,7 +5,7 @@ import Updux, { createAction } from './index.js';
describe('basic selectors', () => {
type State = { x: number };
const foo = new Updux({
const config = {
initialState: {
x: 1,
},
@ -19,12 +19,20 @@ describe('basic selectors', () => {
getY: ({ y }: { y: number }) => y,
getYPlus:
({ y }) =>
(incr: number) =>
(y + incr) as number,
(incr: number) =>
(y + incr) as number,
},
}),
// cause the type to fail
baz: new Updux({
selectors: {
getFromBaz: () => 'potato',
},
}),
},
});
};
const foo = new Updux(config);
const sample = {
x: 4,

View File

@ -3,23 +3,25 @@ import { DuxState, UnionToIntersection } from './types.js';
type RebaseSelectors<SLICE, DUX> = DUX extends { selectors: infer S }
? {
[key in keyof S]: RebaseSelector<SLICE, S[key]>;
}
[key in keyof S]: RebaseSelector<SLICE, S[key]>;
}
: never;
type RebaseSelector<SLICE, S> = SLICE extends string
? S extends (state: infer STATE) => infer R
? (state: Record<SLICE, STATE>) => R
: never
? (state: Record<SLICE, STATE>) => R
: never
: never;
type Values<X> = X[keyof X];
export type DuxSelectors<D> = (D extends { selectors: infer S } ? S : {}) &
(D extends { subduxes: infer SUB }
? Values<{
[key in keyof SUB]: RebaseSelectors<key, SUB[key]>;
}>
? UnionToIntersection<
Values<{
[key in keyof SUB]: RebaseSelectors<key, SUB[key]>;
}>
>
: {});
export function buildSelectors(localSelectors = {}, subduxes = {}) {