0

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

Alfred
  • 427
  • 5
  • 10

3 Answers3

2

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);
     ...
}
Porcellus
  • 559
  • 2
  • 5
0

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

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`
}
Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47