Assigning generic to rest argument and having optional / default arguments

人盡茶涼 提交于 2019-12-11 17:00:02

问题


I am trying to create this function below that takes one optional argument. It's an object, and the only prop needed is value however, I am looking to pass along any ...rest parameters that area also passed in.

const useHook = <T extends { value: string }>({
   value: v = '',
   ...props
}: T = { value: '' } as T) => {
    const defaultValue = React.useMemo(() => v, [props])
    const [value, setValue, resetValue] = Hooks.useState(defaultValue)
    const onChange = React.useCallback((e) => setValue(e.target.value), [setValue])
    return tuple({ value, onChange, ...props }, { defaultValue, resetValue, setValue })
}

Here are the expected cases that should work:

const [props1] = useHook({ value: '12345', name: 'Thomas' }) // works
const [props2] = useHook({ name: 'Thomas' }) // doesn't work missing "value"
const [props3] = useHook() // works
const [props4] = useHook({}) // doesn't work missing "value"

const x = props1.name // string

How can I make value optional?

Here's what I am looking for:

  • Optional value prop has to be string
  • ...props are within the first returned tuple
  • All of the argument options supported above

Playground link

来源:https://stackoverflow.com/questions/58827771/assigning-generic-to-rest-argument-and-having-optional-default-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!