typescript document.getElementById("id") 可能为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43218680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:25:25  来源:igfitidea点击:

document.getElementById("id") may be null

typescripttypescript2.0

提问by Evan Hefner

Edit: I'm using TypeScript v2.2.1

编辑:我使用的是 TypeScript v2.2.1

I am new to TypeScript and I'm not sure what the cleanest way of dealing with DOM elements that may or may not exist is. Basically, I want to check whether an element exists, and then if it does, add an event listener to it (I have --strict_null_checksturned on).

我是 TypeScript 的新手,我不确定处理可能存在或不存在的 DOM 元素的最干净的方法是什么。基本上,我想检查一个元素是否存在,然后如果存在,则为其添加一个事件侦听器(我已--strict_null_checks打开)。

When I do it the JS-like way:

当我以类似 JS 的方式执行此操作时:

const myElement = document.getElementById('my-id');
if (myElement) {
  myElement.addEventListener('click', (e:Event) => {
    // Do stuff.
  });
}

I get the error my_script.ts(3, 3): error TS2531: Object is possibly 'null'.

我收到错误 my_script.ts(3, 3): error TS2531: Object is possibly 'null'.

I can get around this by using a not-null assertion:

我可以通过使用非空断言来解决这个问题:

const maybeMyElement = document.getElementById('my-id');
if (maybeMyElement) {
  const myElement = maybeMyElement!;
  myElement.addEventListener('click', (e:Event) => {
    // Do stuff.
  });
}

But my understanding is that those sorts of assertions are generally frowned upon, and aesthetically, I don't like creating twice as many variables.

但我的理解是,这些类型的断言通常是不受欢迎的,而且在美学上,我不喜欢创建两倍多的变量。

Is there a cleaner way to do this?

有没有更干净的方法来做到这一点?

回答by ps2goat

You should type your variables. I haven't done a lot with const, but your second options seems plain wrong (code-smell).

你应该输入你的变量。我没有做过很多事情const,但你的第二个选项似乎完全错误(代码味道)。

You should be able to get around the warning by strictly typing the variable. The compiler currently sees this as

您应该能够通过严格输入变量来绕过警告。编译器目前将此视为

const myElement: HTMLElement = document.getElementById('my-id');

If you change it to also possibly be null, then nulls are allowed:

如果您将其更改为也可能为空,则允许为空:

const myElement: HTMLElement | null = document.getElementById('my-id');

Updated

更新

Second option (that I haven't tried): use the !at the end of the potentially null operation, per https://stackoverflow.com/a/40640854/2084315

第二个选项(我还没有尝试过):!根据https://stackoverflow.com/a/40640854/2084315,在可能为空的操作结束时使用

const myElement = document.getElementById('my-id')!;

回答by Amy

Try using the following:

尝试使用以下方法:

if (!!myElement) {
    myElement.addEventListener('click', (e:Event) => {
        // Do stuff.
    });
}

The !!coerces an object expression into a boolean. It's the !operator twice. For more info on this, see this answer

!!对象表达式强制转换为布尔值。!两次都是操作员。有关这方面的更多信息,请参阅此答案