Type of property value in generic object

I’m trying to type the value parameter of the setObject function :

type setValueType<T> = (newValue: T) => void

const useObject = () => {
    const setObject = <T>(property: string, value: any, object: T, setValue: setValueType<T>) => {
        setValue({
            ...object,
            [property]: value
        })
    }

    return {
        setObject
    }
}

export default useObject

But I don’t know what to put for the value type. I want that value to be type of T[property] but I don’t know how to make this…

Answer

You just need to add more generics:

type setValueType<T> = (newValue: T) => void

const useObject = () => {
  const setObject = <
    Obj,
    Prop extends keyof Obj,
    Value extends Obj[Prop]
  >(property: Prop, value: Value, object: Obj, setValue: setValueType<Obj & Record<Prop, Value>>) => {
    setValue({
      ...object,
      [property]: value
    })
  }

  return {
    setObject
  }
}

export default useObject

Prop generic represents object key/prop

Obj generic represents object

Value generic represents new value

Let me know if it works for you