【发布时间】:2020-02-03 02:06:29
【问题描述】:
我正在尝试向旧组件添加类型注释,但不确定connect 的类型是否支持我正在尝试做的事情。该组件是一个连接组件,它接收一个广泛类型的 prop,然后使用该 prop 在 state 中查找一个值,并吐出一个较窄的 prop。
目前,我可以使用广泛的类型定义道具,并且代码将起作用。但是,我在组件中编写的任何代码都必须符合这种广泛的类型,即使我知道它已经被缩小了。因此,为了满足打字稿的要求,我要么必须添加类型断言,要么添加不必要的类型检查。
下面是显示行为的代码的简化示例:
interface ExampleProps {
thing: string | number;
}
const Example extends React.Component<ExampleProps> {
render() {
const problem = this.props.thing * 2; // type error
// Workaround, but losing some typesafety
// const notAProblem = (this.props.thing as number) * 2;
// Workaround, but doing unnecessary checks
// if (typeof this.props.thing === 'number') {
// const notAProblem = this.props.thing * 2;
// }
return null;
}
}
const mapStateToProps = (state: RootState, otherProps: ExampleProps) => {
if (typeof otherProps.thing === 'string') {
return {
thing: state.lookup[otherProps.thing]; //resolves to a number
}
}
return {
thing, // also a number
}
}
export default connect(mapStateToProps)(Example)
在上面的代码中,typescript 正确地指出 const problem: number = this.props.thing * 2; 是一个问题。对于我定义的类型,this.props.thing 可能是一个字符串,所以它正确地给出了错误The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
是否可以使用connect 以使不同的道具进来而不是出去?换句话说,我需要有人能够渲染<Example thing={2} /> 或<Example thing={"2"} />,但是对于示例中的代码来说,由于mapStateToProps,thing 只能是number
【问题讨论】:
-
我认为你只需要在计算之前进行类型检查就可以在
Example中使用 type-guard
标签: reactjs typescript react-redux