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', () => { describe('basic selectors', () => {
type State = { x: number }; type State = { x: number };
const foo = new Updux({ const config = {
initialState: { initialState: {
x: 1, x: 1,
}, },
@ -19,12 +19,20 @@ describe('basic selectors', () => {
getY: ({ y }: { y: number }) => y, getY: ({ y }: { y: number }) => y,
getYPlus: getYPlus:
({ y }) => ({ y }) =>
(incr: number) => (incr: number) =>
(y + incr) as number, (y + incr) as number,
},
}),
// cause the type to fail
baz: new Updux({
selectors: {
getFromBaz: () => 'potato',
}, },
}), }),
}, },
}); };
const foo = new Updux(config);
const sample = { const sample = {
x: 4, x: 4,

View File

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