Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/cuppachino/typed-create

zustand-like store with type inference
https://github.com/cuppachino/typed-create

store zustand

Last synced: 22 days ago
JSON representation

zustand-like store with type inference

Awesome Lists containing this project

README

        

# typed-create

```ts
export const create = (base: T) => {
let state = base
const api = {
_setState(newState: U | T): void {
state = { ...state, ...newState } as T & U
},
setState(newState: T | Partial): void {
state = { ...state, ...newState }
},
getState(): T {
return state
}
}

return (actions: (set: typeof api.setState, get: typeof api.getState) => U) => {
api._setState({
...api,
...actions(api.setState, api.getState)
})
return {
getState: api.getState,
setState: api.setState
} as _InternalCreateApi
}
}
```
```ts
export interface CreateApi {
getState: () => T;
setState: (newState: T | Partial) => T;
}

type _InternalCreateApi = CreateApi<{
[K in keyof T | keyof U]: K extends keyof T
? T[K]
: K extends keyof U
? U[K]
: never;
}> extends CreateApi
? CreateApi
: never;
```

In response to [this](https://stackoverflow.com/questions/70758462/how-to-infer-a-functions-parameter-type-from-its-return-type) question on stackoverflow

[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/scavdk)