JSDoc 非空断言

问题描述 投票:0回答:2

在 javascript 中,使用 JSDoc,我正在查询页面上的元素:

// @ts-check

/** @type {HTMLInputElement} */
const element = document.getElementById('checkbox');

但我收到警告:

输入“HTMLElement | null' 不可分配给类型'HTMLInputElement'。 类型“null”不可分配给类型“HTMLInputElement”.ts(2322)

有没有办法断言此类型不为空,就像在打字稿中使用

!
运算符所做的那样?

javascript jsdoc
2个回答
7
投票

查看文档后,这可以使用内联casting来完成。所以在你的情况下,正确的代码应该是这样的:

// @ts-check

const element = /** @type {HTMLInputElement} */ (document.getElementById('checkbox'));

此外,请确保在

/** @type {...} */
注释之后需要使用括号将代码括起来。


0
投票

这里有一个更好的方法,这样你就不必总是写出值的确切类型,更像是 TS 中非空运算符的便利:

/**
 * In lieu of writing in TypeScript and having the convenient non-null assertion
 * operator (!), this helper function allows asserting that something is not
 * null or undefined without having to write a JSDoc type cast that has to
 * explicitly know the non-null type (which is error prone).
 *
 * For example, insgtead of having to write this:
 *
 * ```js
 * const value = /** @​type {SomeNullableType} *​/(possiblyNullValue)
 * ```
 *
 * we can write this:
 *
 * ```js
 * const value = NonNull(possiblyNullValue)
 * ```
 *
 * @template {any} T
 * @param {T} item
 */
function NonNull(item) {
    if (item === null || item === undefined) throw 'item is null or undefined'
    return item
}

在这个例子中,

div
的类型将是
HTMLDivElement
,而不是
HTMLDivElement | null
,根据需要(另外,如果你实际上错了,它会抛出,这可能更理想!):

const div = NonNull(document.querySelector('div'))

使用和不使用

NonNull
的 VS Code 中类型感知的屏幕截图:

© www.soinside.com 2019 - 2024. All rights reserved.