StrictNullChecks 和 getElementById [英] StrictNullChecks and getElementById

查看:31
本文介绍了StrictNullChecks 和 getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript 2.0 中启用 StrictNullChecks 后,代码

With StrictNullChecks enabled in TypeScript 2.0, the code

var el: HTMLElement = document.getElementById('element_id');

产生错误

Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
Type 'null' is not assignable to type 'HTMLElement'.

为什么会这样?我怎样才能在不使 el 为空的情况下编译代码?

Why is this and how can I get the code to compile without making el nullable?

推荐答案

你可以写:

var el = document.getElementById('element_id')!;

!意思是相信我,这不是空引用"

The ! means "trust me, this is not a null reference"

这篇关于StrictNullChecks 和 getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆