W
W
wvw12022-04-15 11:45:11
typescript
wvw1, 2022-04-15 11:45:11

Function1 takes function2 as arguments. How can function3 be passed arguments to function2's argument types + one more?

import { useState, useEffect, FC } from 'react'

interface UseControlledProps<Value, ChangeHandler> {
  defaultValue: Value
  onChange: ChangeHandler // (...args: any) => any
  // вот как мне задать это значение?
}

function useControlled<Value, ChangeHandler>({
  defaultValue,
  onChange
}: UseControlledProps<Value, ChangeHandler>) {
  //
  const [state, setState] = useState(defaultValue)

  useEffect(() => {
    if (defaultValue !== state) {
      setState(defaultValue)
    }
  }, [defaultValue])

  type Params = Parameters<ChangeHandler> // Type 'ChangeHandler' does not satisfy the constraint '(...args: any) => any'

  return [
    state,
    //
    (value: Value, ...params: Params) => {
      setState(value)
      onChange(...params)
    },
  ] as const
}

interface CustomInputProps {
  defaultValue: string
}

// пример использования
const CustomInput: FC<CustomInputProps> = ({ defaultValue }) => {
  const onChange = (str: string, ggg?: boolean) => {
    console.log(str) // бульбульбуль
  }

  const [value, setValue] = useControlled({ defaultValue, onChange })

  const handleInput = (event) => {
    setValue(event.target.value, 'бульбульбуль') //
  }

  return <input value={value} onChange={handleInput} />
}


625943b809c29588438792.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question