打字稿中键入不匹配并做出反应

时间:2019-07-26 10:59:58

标签: reactjs typescript types

我对打字稿有疑问并做出反应。贝娄是一个说明问题的小例子。

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是否已定义,但打字稿不会编译它,因为fn要求x为数字。可以使用铸造

来解决
const y = props.x as number;
return <button onClick={() => props.fn(y)}>Click me</button>

它有效,但看起来很奇怪。任何想法如何处理这种情况。这只是我的代码中的一个示例,我们有一个对象而不是数字,它也已定义,然后为它呈现或未定义(===未定义)呈现一些html,然后我们只返回null。

1 个答案:

答案 0 :(得分:3)

这是控制流分析工作方式的限制。该分析不会跨越功能边界。您可以阅读更多here。基本思想是无法保证在调用回调时prop.x仍不会undefined

解决方法是将prop.x放在局部变量中。这将捕获变量类型中的流类型:


const Example = (props: { x?: number, fn: (x: number) => void}) => {
        if (props.x !== undefined) {
            const x = props.x
            return <button onClick={() => props.fn(x)}>Click me</button>
        }
        return null;
}

相关问题