2

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...

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, it works like a charm. But it's normal that we don't have to provide a value for the Prop generic and the Value generic ?
@AdriHM Prop and Value generics serves as constraints for our function. Once you provide object argument, TS will infer all other generics

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.