谁知道img.src!后面的!是什么意思

新手上路,请多包涵

这是ng-zorro的Upload的下面的代码,不知道里面跟在属性后面的!是什么意思,主要是tslint一直报错,不知道如何处理

private checkImageDimension(file: File): Promise<boolean> {

return new Promise(resolve => {
  const img = new Image(); // create image
  img.src = window.URL.createObjectURL(file);
  img.onload = () => {
    const width = img.naturalWidth;
    const height = img.naturalHeight;
    window.URL.revokeObjectURL(img.src!);
    resolve(width === height && width >= 300);
  };
});

}

handleChange(info: { file: UploadFile }): void {

switch (info.file.status) {
  case 'uploading':
    this.loading = true;
    break;
  case 'done':
    // Get this url from response in real world.
    this.getBase64(info.file!.originFileObj!, (img: string) => {
      this.loading = false;
      this.avatarUrl = img;
    });
    break;
  case 'error':
    this.msg.error('Network error');
    this.loading = false;
    break;
}

}

阅读 2.7k
1 个回答

typescript 编译器发现该值在使用的时候可能为 null。在我们明确知道有值的所以我们肯定不能一直 if 判断。而ts又没法判断这里一定有值。
所以ts就折衷处理,某些时候交给用户处理
!表示强制解析(也就是告诉typescript编译器,我这里一定有值)
同时也可以看看 es 的新提案链判断运算符,感觉更为灵活好用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题