这里的最好方式是,你不必总是写出价值的确切类型,更像在多边贸易体系中非致命操作者的方便性:
/**
* 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
}
In this example, the type of div
will be HTMLDivElement
, not HTMLDivElement | null
, as desired (plus it will throw if you are actually wrong, which may be even more desirable!):
const div = NonNull(document.querySelector( div ))
• 《联邦法典》中含有且未使用的类型认识的筛选: