#How do I dynamically add methods to a object while retaining types?

13 messages · Page 1 of 1 (latest)

stoic vaporBOT
#
didyouknowthis#0

Preview:```ts
export type StoreOptions<
S,
A extends Record<string, (...args: any[]) => any>,
G

= {
state: () => S
actions: {
[K in keyof A]: (
state: S,
...args: Parameters<A[K]>
) => any
}
getters: {[K in keyof G]: (state: S) => G[K]}
}

export type Store<
S,
A extends Record<string, (...args: any[]) => any>,
G

= S & {
[K
...```

short mason
#

I'm not sure where in your code the issue is

#

but generally you either need an indexer like

type O = {
    [key: string]: (A) => B
}
#

or you need to create a function that takes an object and new method, and returns an object with a new shape

#
function add<O extends object, K extends string, M extends Function>(o: O, k: K m: M): O & { [Key in K]: M } {
    // 
}
#

but you need a functional style for that to be useful, its not really fully dynamic

violet gyro
#

I created a action type type ActionFunction<S, Args extends any[], Result> = (state: S, ...args: Args) => Result;

#

Now it understands the increments type

#

@short mason Here's the working version. There's still a lot to be done to handle more use cases, like not needing to pass the state to actions, etc. But this at least works!

stoic vaporBOT
#
didyouknowthis#0

Preview:```ts
export type StoreOptions<
S,
A extends Record<string, (...args: any[]) => any>,
G

= {
state: () => S
actions: A
getters: {[K in keyof G]: (state: S) => G[K]}
}

type ActionFunction<S, Args extends any[], Result> = (
state: S,
...args: Args
) => Result
...```

short mason
#

Cool