Gre*_*een 10 generics typescript reactjs
我想为 React props 扩展一个接口。但我收到 TS 错误错误:(19, 35) TS2304: 找不到名称 'T'。
1)为什么会出错?<T>是泛型。不能在使用前声明。
2) 为什么 TS 在我的代码中抛出错误,但没有在此处抛出绝对类型的 React 类型定义。泛型类型<T>和许多其他类型在其代码中随处可见。他们为什么不扔?
3)如何以正确的方式扩展它?
这是我的代码。
我从DefineTyped 为 React导入接口 Props:
import React, {Props, PureComponent} from 'react';
// TS throws Error:(20, 27) TS2304: Cannot find name 'T'.
interface IHomeProps extends Props<T> { }
class Home extends PureComponent<IHomeProps> {
render() {
...
}
}
// interface Props definition
interface Props<T> {
children?: ReactNode;
key?: Key;
ref?: LegacyRef<T>;
}
Run Code Online (Sandbox Code Playgroud)
您需要T在您定义的接口上指定一个具体的或声明一个泛型类型参数。
在反应定义中,代码有效,因为它们确实定义T了<T>接口之后是 for 的定义T,因此它可以在接口内部使用。定义自己的接口时,需要定义自己的类型参数T,然后将if转发到Props。这是定义的版本的T样子:
interface IHomeProps<T> extends Props<T> { }
// ^ T is defined ^ T is used
Run Code Online (Sandbox Code Playgroud)
您可能只想为 提供一个具体类型T:
interface IHomeProps extends Props<HTMLDivElement> { }
class Home extends PureComponent<IHomeProps> {
render() {
return <div></div>
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10575 次 |
| 最近记录: |