【问题标题】:Type mismatch in typescript and react打字稿中的类型不匹配并做出反应
【发布时间】: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


    【解决方案1】:

    这是控制流分析工作方式的一个限制。分析不跨越功​​能边界。你可以阅读更多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;
    }
    
    

    【讨论】:

    • 谢谢,它工作了,现在看起来好多了,还是有点奇怪,但至少没有演员表。
    • 重点是这是回调。在通话时,您的 x 在理论上可能是未定义的。
    • @JurajKocan 10x,添加到答案中,我很懒惰,好东西所以社区让我诚实?
    猜你喜欢
    • 2018-03-22
    • 2022-01-21
    • 2019-09-03
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2021-09-11
    • 2018-03-27
    • 2017-06-24
    相关资源
    最近更新 更多