S
SolidJS13mo ago
Tianyi

Add types to context provider

Can someone help me out here, please? For this example from the official doc https://www.solidjs.com/tutorial/stores_context?solved How do you add types to the Counter.jsx as in convert Counter.jsx to Counter.tsx.
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
2 Replies
thetarnav
thetarnav13mo ago
createContext takes a type parameter that you can use to set the type of the context value. in this case it will be something like this
type CounterActions = {
increment: () => void,
decrement: () => void,
}

type CounterState = [
count: solid.Accessor<number>,
actions: CounterActions
]

const CounterContext = solid.createContext<CounterState>()
type CounterActions = {
increment: () => void,
decrement: () => void,
}

type CounterState = [
count: solid.Accessor<number>,
actions: CounterActions
]

const CounterContext = solid.createContext<CounterState>()
This will cause the type of the context to be CounterState | undefined though If you want to assert that the context is always present you can use this pattern:
const CounterContext = solid.createContext({} as any as CounterState)
const CounterContext = solid.createContext({} as any as CounterState)
Also if you would like to infer the context type instead of manually typing what it is supposed to be you can extract the creation of counter state to a separate function
function createCounterState(initialCount = 0) {
const [count, setCount] = solid.createSignal(initialCount)

return [
count,
{
increment: () => setCount(c => c + 1),
decrement: () => setCount(c => c - 1)
}
] as const;
}

type CounterState = ReturnType<typeof createCounterState>
function createCounterState(initialCount = 0) {
const [count, setCount] = solid.createSignal(initialCount)

return [
count,
{
increment: () => setCount(c => c + 1),
decrement: () => setCount(c => c - 1)
}
] as const;
}

type CounterState = ReturnType<typeof createCounterState>
Tianyi
Tianyi13mo ago
Thank you! that worked perfectly!
Want results from more Discord servers?
Add your server