I'm trying to make a custom "hook" for solid-js that will retrieve state from local storage.
import { Accessor, createSignal, Setter } from "solid-js";
export default function createLocalStorageSignal<T extends string>(key: string): [get: Accessor<T>, set: Setter<T>] {
const storage = window.localStorage;
const initialValue: T = JSON.parse(storage.getItem(key) ?? '{}').value;
const [value,setValue] = createSignal<T>(initialValue);
const newSetValue: Setter<T> = (newValue) => {
setValue(newValue);
storage.setItem(key, JSON.stringify({value: newValue}));
return newValue;
}
return [
value,
newSetValue
]
}
However I get the type error
Type '(newValue: any) => void' is not assignable to type 'Setter<T>'
Why can't newValue's type be inferred? and if it can't be inferred what do I set it to?
EDIT:
Setter<T>
's full type is
type Setter<T> = undefined extends T ?
<U extends T>
(v?: (U extends Function ? never : U) |
((prev?: T | undefined) => U) | undefined) => U :
<U extends T>
(v: (U extends Function ? never : U) |
((prev: T) => U)) => U
I don't exactly understand the purpose of the U
type and how it works. I think the problem relates to the fact that newValue could potentially be a function but the T type could also be a function type or something...