Reputation: 447
I am building a custom hook and I want to set the state type the same as the initial state type
const useCustomHook = (initialState)=>{
...
const [state,setState] = useState<someDynamicType>(initialState);
...
}
How can I do this? Initial state could be anything and not always the same type
Upvotes: 0
Views: 659
Reputation: 191976
Use generics to add a type to the initialState
, and the useState
hook:
const useCustomHook = <T>(initialState: T)=>{
...
const [state,setState] = useState<T>(initialState);
...
}
When using the custom hook, the state would get the type of the initial state. For example:
const x = null
useCustomHook(x)
In this case the state type would be null
. In cases like that you can explicitly set the type:
type X = { a: boolean, b: string }
useCustomHook<X | null>(x)
Upvotes: 0
Reputation: 579
You could pass someDynamicType
as a type parameter to the function. It's a bit more convenient if you use an anonymous function instead of a lambda:
const useCustomHook = function<T>(initialState: T) {
...
const [state,setState] = useState<T>(initialState);
...
}
You could also use a lambda, but the syntax is a bit more clunky: (explained here)
const useCustomHook = <T extends unknown>(initialState: T) => {
...
const [state,setState] = useState<T>(initialState);
...
}
Upvotes: 2
Reputation: 10153
You can use a generic type as documented here: https://www.typescriptlang.org/docs/handbook/2/generics.html
const useCustomHook = <T>(initialState:T) => {
const [state,setState] = useState<T>(initialState);
// state is now `T`
}
Upvotes: 0