【问题标题】:Typescript : cannot read property 'long_name' of null打字稿:无法读取 null 的属性“long_name”
【发布时间】:2017-06-15 10:25:56
【问题描述】:

我尝试使用Non-null assertion operator,如我的代码下方的TypeScript official documentation. 所示:

    let streetNumberComponent  = this.getAddressComponent(addressComponents, 'street_number');
    address.streetNumber = streetNumberComponent!.long_name();

    ...

    public getAddressComponent(addressComponents: Array<any>, type: string): any {

        addressComponents.filter( component => {
            let types : Array<string> = component.types;
            if(_.includes(types, type)) {
                return component;
            }
        });

        return null;
    }

我预计只有在streetNumberComponent 不是null 时才能访问属性long_name()。但事实并非如此,我明白了:

TypeError: Cannot read property 'long_name' of null

请注意,以下代码可以正常工作:

address.streetNumber = streetNumberComponent && streetNumberComponent.long_name();

我正在使用:

  • 打字稿:2.0.10
  • 角度:2.3.1
  • Angular CLI:1.0.0-beta.24

【问题讨论】:

  • streetNumberComponent!.long_name(); 写你的问题时那个感叹号是错字吗?
  • 这是 TypeScript Non-null assertion operator
  • 哦,对了,我的错,在TS上没做过那么多哈哈。

标签: javascript angular typescript typeerror angular-cli


【解决方案1】:

Non-null 断言运算符仅在 typescript 中使用,它在编译过程中不存在,并且不存在于 js 代码中。如文档中所述:

!非空断言运算符只是在发出的 JavaScript 代码

这个运算符并不真正检查它之前的内容是否为空,它只是一种告诉编译器你确定它不为空的方式,即使编译器自己无法推断.

显然,当您运行此代码时,streetNumberComponent 为空。

【讨论】:

  • 谢谢尼赞。这种运营商的真正用途是什么?我看不到它的具体用法!
  • 他们在您问题链接中的示例显示了这种情况。有时您比编译器了解更多,因此该语言引入了不同的方法来纠正编译器,其中一种是 this 运算符,另一种是强制转换/类型断言。
猜你喜欢
  • 2019-01-22
  • 2019-01-31
  • 2021-11-03
  • 2017-07-21
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多