简体   繁体   English

打字稿中的类型不匹配并做出反应

[英]Type mismatch in typescript and react

I have an issue with typescript and react. 我有打字稿和反应的问题。 Bellow is a small exmaple that illustrates the problem. 贝娄是一个小例子,说明了这个问题。

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;
}

Code checks explicitly that x is defined but typescript won't compile it because fn requires x to be a number. 代码检查显式定义了x,但typescript不会编译它,因为fn要求x为数字。 It can be solved using casting 它可以使用铸造来解决

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

It works but looks weird. 它有效,但看起来很奇怪。 Any ideas how to handle such cases. 任何想法如何处理这种情况。 It's just an example in my code we have an object instead of a number and it also either defined and then we render some html for it or not defined (=== undefined) and than we just return null. 它只是我的代码中的一个例子,我们有一个对象而不是一个数字,它也要么被定义,然后我们为它渲染一些html或者没有定义(=== undefined),而不是我们只返回null。

This is a limitation in how control flow analysis works. 这是控制流分析如何工作的限制。 The analysis does not cross function boundaries. 分析不跨越功​​能边界。 You can read more here . 你可以在这里阅读更多。 The basic idea is that there is no guarantee prop.x will still not be undefined by the time the callback is called. 基本思想是无法保证prop.x在调用回调时仍然不会被undefined

The workaround is to put prop.x in a local variable. 解决方法是将prop.x放在局部变量中。 This will capture the flow type in the variable type: 这将捕获变量类型中的流类型:


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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM