[英]Typescript React forwardRef with Union/Generic Element
[英]Using React forwardRef with Typescript generic JSX arguments
給定以下使用泛型類型參數的類型化React組件,我該如何將其包裝在React的新forwardRef
API中?
type Props<T> = {
forwardedRef?: Ref<HTMLInputElement>
...
}
class GenericComponent<T> extends Component<Props<T>> {
...
}
const ComponentWithRef = forwardRef<HTMLInputElement, Props<T>>((props, ref) => (
<StringInput<T> {...props} forwardedRef={ref} />
))
上述方法無法定義T
泛型。
因此,為了擴大問題范圍,這實際上是關於在更高階函數中保留泛型類型的問題。 以下對forwardRef
用法將正確地進行類型檢查(在3.0.1
)
const SelectWithRef = forwardRef(<Option extends string>(props: Props<Option>, ref?: Ref<HTMLSelectElement>) =>
<Select<Option> {...props} forwardedRef={ref} />);
但是, Option
泛型會立即解析為string
,而不是保留為泛型。 因此,以下內容不會進行類型檢查
const onChange: (value: 'one' | 'two') => void = (value) => console.log(value);
<SelectWithRef<'one' | 'two'>
^^^^^^^^^^^^^^^ [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"'
/>
在此Typescript發行票證中跟蹤了相關的發行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.