gpt4 book ai didi

typescript - StrictNullChecks 和 getElementById

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:08 25 4
gpt4 key购买 nike

在 TypeScript 2.0 中启用 StrictNullChecks 后,代码

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 为空的情况下编译代码?

最佳答案

你可以这样写:

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

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

关于typescript - StrictNullChecks 和 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40640663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com