【发布时间】:2019-12-04 17:15:47
【问题描述】:
我对打字稿有疑问并做出反应。 Bellow 是一个说明问题的小例子。
const Example = (props: { x?: number, fn: (x: number) => void}) => {
if (props.x !== undefined) {
return <button onClick={() => props.fn(props.x)}>Click me</button>
}
return null;
}
代码明确检查 x 是否已定义,但 typescript 不会编译它,因为 fn 要求 x 是一个数字。可以使用强制转换来解决
const y = props.x as number;
return <button onClick={() => props.fn(y)}>Click me</button>
它有效,但看起来很奇怪。任何想法如何处理这种情况。这只是我的代码中的一个示例,我们有一个对象而不是一个数字,它也已定义,然后我们为它渲染一些 html 或未定义(=== 未定义),然后我们只返回 null。
【问题讨论】:
标签: reactjs typescript types