Using React forwardRef with Typescript generic JSX arguments

后端 未结 1 1671
遇见更好的自我
遇见更好的自我 2021-01-04 03:05

Given the following typed React component using generic type arguments, how would I go about wrapping it in React\'s new forwardRef API?

type Pr         


        
1条回答
  •  有刺的猬
    2021-01-04 03:22

    So, to broaden the question some, this is really a question about preserving generic types in higher order functions. The following usage of forwardRef will properly typecheck (in 3.0.1)

    const SelectWithRef = forwardRef(

    But, the Option generic is immediately resolved to string, rather than remaining as a generic. As such, the following does not typecheck

    const onChange: (value: 'one' | 'two') => void = (value) => console.log(value);
    
    
                  ^^^^^^^^^^^^^^^ [ts] Expected 0 type arguments, but got 1
      value="a"
      options={['one', 'two']}
      onChange={onChange}
               ^^^^^^^^^^ [ts] Type 'string' is not assignable to type '"one" | "two"'
    />
    

    The relevant issue is tracked in this Typescript issue ticket.

    0 讨论(0)
提交回复
热议问题