Jam*_*ing 20 typescript reactjs
鉴于以下使用泛型类型参数的类型化 React 组件,我将如何将其包装在 React 的新forwardRefAPI 中?
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} />
))
Run Code Online (Sandbox Code Playgroud)
上面的方法没有办法定义T泛型。
Jam*_*ing 19
因此,将问题扩大一些,这实际上是一个关于在高阶函数中保留泛型类型的问题。以下用法forwardRef将正确类型检查 (in 3.0.1)
const SelectWithRef = forwardRef(<Option extends string>(props: Props<Option>, ref?: Ref<HTMLSelectElement>) =>
<Select<Option> {...props} forwardedRef={ref} />);
Run Code Online (Sandbox Code Playgroud)
但是,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"'
/>
Run Code Online (Sandbox Code Playgroud)
相关问题在此 Typescript issue ticket 中进行了跟踪。
| 归档时间: |
|
| 查看次数: |
9969 次 |
| 最近记录: |