我正在尝试升级 React-Redux 项目中的 typescript 依赖项 (2.5.x > 3.1.3)。遗憾的是并非没有问题:P
我有一个基本的 selectpicker React 组件,它需要一个带有 IdNameObject 类型参数的函数属性:
onToggleItem: (item: IdNameObject) => void;
注入(inject)到 function prop 中的实际函数是一个 Redux 调度函数,其参数是扩展 IdNameObject 的接口(interface):
updateSelectedLocation: (location: Location) => void;
interface Location extends IdNameObject {...}
显然,Typescript 现在会抛出一个错误,指出类型 Location 不等于类型 IdNameObject。
我尝试转换函数属性以使其通用:
onToggleItem: <T extends IdNameObject>(item: T) => void
但这仍然会引发 typescript 错误:
type '(location: Location) => void' is not assignable to type '<T extends IdNameObject>(item: T) => void'
知道在这种情况下我应该做什么吗?
<小时/>完整示例案例
我省略了本例中并不真正需要的所有额外代码。
一侧有一个 navigation.tsx:
interface Location extends IdNameObject {...}
interface Props {
updateSelectedLocation: (location: Location) => void;
}
class Navigation extends React.Component<Props> {
public render(): any {
const {updateSelectedLocation} = this.props;
return <Selectpicker onToggleItem={updateSelectedLocation}/>;
}
}
function mapDispatchToProps(dispatch: DispatchType) {
return {
updateSelectedLocation: (location: Location) => {
dispatch(updateSelectedLocation(location));
},
}
}
export default connect<StateProps, DispatchProps, OwnProps>(mapStateToProps, mapDispatchToProps)((Navigation as any));
在另一边我有一个 selectpicker.tsx:
接口(interface)位置扩展 IdNameObject {...}
interface Props {
onToggleItem: (item: IdNameObject) => void;
}
export class Selectpicker extends React.Component<Props> {
public render(): any {
const {onToggleItem} = this.props;
return <Dropdown contentOnToggleItem={onToggleItem}/>;
}
}
最佳答案
通过定义类型参数T
上onToggleItem
,您说过 selectpicker 组件的每个调用者都必须提供 onToggleItem
适用于每个 T
的实现。我认为你想要的是 selectpicker 组件的调用者选择类型 T
构造选择器时选择的对象的数量,然后提供 onToggleItem
适用于该特定 T
的实现。为此,T
应该在 selectpicker 组件和包含 onToggleItem
的 props 接口(interface)上定义(如果您正在使用一个),而不是 onToggleItem
本身。
如果您在执行此操作时遇到困难,请在问题中添加更多代码(至少是 selectpicker 类的声明)。
更新
根据示例代码,以下是添加 T
的方法至selectpicker.tsx
:
interface Props<T extends IdNameObject> {
onToggleItem: (item: T) => void;
}
export class Selectpicker<T extends IdNameObject> extends React.Component<Props<T>> {
public render(): any {
const {onToggleItem} = this.props;
return <Dropdown contentOnToggleItem={onToggleItem}/>;
}
}
然后,在 navigation.tsx
,TypeScript 应该推断出你的 <Selectpicker ... />
元素正在使用 T = Location
。您还可以显式指定 <Selectpicker<Location> ... />
.
关于javascript - 使用 typescript 3.1.3 将 React-Redux 调度定义为通用函数属性会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52870344/