typescript泛型和类属性 | 珊瑚贝

Typescript generics and class properties


我目前正在一个 React 项目中使用 Typescript,并希望使用类属性来设置初始状态,但是在使用未定义的值和严格的 null 检查时遇到了一些问题。这是我的问题的最小重构,没有任何 React 特定代码来演示我的问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Component< T > {
    state: T;
}

interface Foo {
    bar: number | undefined
}

class Test extends Component<Foo> {
    state = {
        bar: undefined
    }

    test(a: number) {
        //
    }

    callTest() {
        if (this.state.bar) {
            this.test(this.state.bar) // Argument of type ‘undefined’ is not assignable to parameter of type ‘number’.
        }
    }
}

TS游乐场链接

所以这个错误只有在启用严格的空检查时才会出现。

还有:

  • 如果我在构造函数中设置状态而不是通过类属性
    没有错误。游乐场

  • 如果我在类属性上显式设置类型,则不会出现错误。游乐场

这是 Typescript 处理不好还是我遗漏了什么/做错了什么?

编辑:看起来 TS-playground 不共享选项,所以请手动检查 sctrictNullChecks 以查看错误。


当您在 Test 中重新声明 state 属性时,它会根据初始值设定项的类型获得一个新类型,即 {bar: undefined},您可以通过将鼠标悬停在 state 上看到。这就是为什么 TypeScript 认为 this.state.bar 不能是 undefined 以外的任何东西,即使在你检查它是真的之后也是如此。在构造函数中初始化 state 是正确的解决方案。


因为 undefined 在 Typescript 中被视为独立类型。您将 undefined 传递给测试函数的类型为 number 的参数。如果您确定您的测试函数可以接受 undefined,只需允许 undefined 作为可接受的参数类型:

1
2
3
test(a: number | undefined) {
        //
}
  • 嗯,对不起,但这不是我想走的路。首先,这没有解释为什么如果我在构造函数中初始化状态,代码会起作用。第二个 test 可能是我无法影响的外部函数。
  • @giggo1604 在这种情况下你能分享你的构造函数吗?如果 test 是一个外部函数,我认为一种选择是在将参数传递给 test 之前进行空值检查。
  • 更新了原帖,请注意编辑评论。感谢您的帮助


来源:https://www.codenong.com/52683678/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9958.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?