]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
feat: mapState with object
authorEduardo San Martin Morote <posva13@gmail.com>
Tue, 6 Apr 2021 18:53:47 +0000 (20:53 +0200)
committerEduardo San Martin Morote <posva@users.noreply.github.com>
Fri, 9 Apr 2021 11:08:56 +0000 (13:08 +0200)
__tests__/mapHelpers.spec.ts
src/mapHelpers.ts

index 4cd6410c98c8e95dc247e754d49a249692899989..1869554aafc4327fd02271db25b27982cc208f80 100644 (file)
@@ -135,6 +135,14 @@ describe('Map Helpers', () => {
       )
     })
 
+    it('object', async () => {
+      await testComponent(
+        mapState(useStore, { count: 'n', myA: 'a' }),
+        `{{ count }} {{ myA }}`,
+        `0 true`
+      )
+    })
+
     it('getters', async () => {
       await testComponent(
         mapState(useStore, ['double', 'notA', 'a']),
index 52ee8bace3b35b7685a902d53941d33c4fddc318..b8ae0a97e178b4aad353cb21722584338a9ce672 100644 (file)
@@ -54,19 +54,55 @@ export function mapStores<Stores extends unknown[]>(
 }
 
 type MapStateReturn<S extends StateTree, G> = {
-  [s in keyof S | keyof G]: () => Store<string, S, G, {}>
+  [key in keyof S | keyof G]: () => Store<string, S, G, {}>[key]
+}
+
+type MapStateObjectReturn<
+  S extends StateTree,
+  G,
+  T extends Record<string, keyof S | keyof G>
+> = {
+  [key in keyof T]: () => Store<string, S, G, {}>[T[key]]
 }
 
 export function mapState<Id extends string, S extends StateTree, G, A>(
   useStore: StoreDefinition<Id, S, G, A>,
   keys: Array<keyof S | keyof G>
-): MapStateReturn<S, G> {
-  return keys.reduce((reduced, key) => {
-    reduced[key] = function () {
-      return useStore((this as any).$pinia)[key]
-    }
-    return reduced
-  }, {} as MapStateReturn<S, G>)
+): MapStateReturn<S, G>
+export function mapState<
+  Id extends string,
+  S extends StateTree,
+  G,
+  A,
+  KeyMapper extends Record<string, keyof S | keyof G>
+>(
+  useStore: StoreDefinition<Id, S, G, A>,
+  keyMapper: KeyMapper
+): MapStateObjectReturn<S, G, KeyMapper>
+export function mapState<
+  Id extends string,
+  S extends StateTree,
+  G,
+  A,
+  KeyMapper extends Record<string, keyof S | keyof G>
+>(
+  useStore: StoreDefinition<Id, S, G, A>,
+  keysOrMapper: Array<keyof S | keyof G> | KeyMapper
+): MapStateReturn<S, G> | MapStateObjectReturn<S, G, KeyMapper> {
+  return Array.isArray(keysOrMapper)
+    ? keysOrMapper.reduce((reduced, key) => {
+        // @ts-ignore: too complicated for TS
+        reduced[key] = function () {
+          return useStore((this as any).$pinia)[key]
+        }
+        return reduced
+      }, {} as MapStateReturn<S, G>)
+    : Object.keys(keysOrMapper).reduce((reduced, key: keyof KeyMapper) => {
+        reduced[key] = function () {
+          return useStore((this as any).$pinia)[keysOrMapper[key]]
+        }
+        return reduced
+      }, {} as MapStateObjectReturn<S, G, KeyMapper>)
 }
 
 /**