Alfred
Alfred

Reputation: 447

How can I dynamically set the type of state inside a custom hook

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

Answers (3)

Ori Drori
Ori Drori

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

Porcellus
Porcellus

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

Sergiu Paraschiv
Sergiu Paraschiv

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

Related Questions