问题
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
valueprop has to bestring ...propsare 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