我有一个类型:

type tSelectProtected = {
  handleSelector?: string,
  data?: tSelectDataItem[],

  wrapperEle?: HTMLElement,
  inputEle?: HTMLElement,
  listEle?: HTMLElement,
  resultEle?: HTMLElement,

  maxVisibleListItems?: number
}

我声明了一个全局模块变量:

var $protected : tSelectProtected = {};

我在function1()范围内分配适当的值:

$protected.listEle = document.createElement('DIV');

稍后在function2()作用域中,我调用:

$protected.listEle.classList.add('visible');

我得到TypeScript错误:

error TS2533: Object is possibly 'null' or 'undefined'

我知道我可以使用if ($protected. listele) {$protected. listele进行显式检查。listEle}使编译器平静下来,但这似乎对于大多数非平凡的情况非常不方便。

在不禁用TS编译器检查的情况下如何处理这种情况?


当前回答

对我来说,这是裁判和反应的错误:

const quoteElement = React.useRef()
const somethingElse = quoteElement!.current?.offsetHeight ?? 0

这将抛出错误,修复,给它一个类型:

// <div> reference type
const divRef = React.useRef<HTMLDivElement>(null);

// <button> reference type
const buttonRef = React.useRef<HTMLButtonElement>(null);

// <br /> reference type
const brRef = React.useRef<HTMLBRElement>(null);

// <a> reference type
const linkRef = React.useRef<HTMLLinkElement>(null);

没有错误了,希望这能在某种程度上帮助到其他人,甚至是我自己,P

其他回答

要解决这个问题,你可以简单地使用感叹号,如果你确定对象在访问它的属性时不是空的:

list!.values

乍一看,有些人可能会把它与angular中的安全导航操作符混淆,但事实并非如此!

list?.values

!后修复表达式将告诉TS编译器变量不是空,如果不是这样,它将在运行时崩溃

useRef

像这样使用useRef钩子

const value = inputRef?.current?.value

在ReactJS中,我检查构造函数中的变量是否为空,如果为空,我将其视为异常并适当地管理异常。如果变量不为空,代码继续运行,编译器在那之后不再抱怨:

private variable1: any;
private variable2: any;

constructor(props: IProps) {
    super(props);

    // i.e. here I am trying to access an HTML element
    // which might be null if there is a typo in the name
    this.variable1 = document.querySelector('element1');
    this.variable2 = document.querySelector('element2');

    // check if objects are null
    if(!this.variable1 || !this.variable2) {
        // Manage the 'exception', show the user a message, etc.
    } else {
        // Interpreter should not complain from this point on
        // in any part of the file
        this.variable1.disabled = true; // i.e. this line should not show the error
    }

这不是OP的问题,但当我意外地将一个参数声明为空类型时,我得到了相同的对象可能是“null”消息:

something: null;

而不是给它赋值为null:

something: string = null;

对我来说,这是裁判和反应的错误:

const quoteElement = React.useRef()
const somethingElse = quoteElement!.current?.offsetHeight ?? 0

这将抛出错误,修复,给它一个类型:

// <div> reference type
const divRef = React.useRef<HTMLDivElement>(null);

// <button> reference type
const buttonRef = React.useRef<HTMLButtonElement>(null);

// <br /> reference type
const brRef = React.useRef<HTMLBRElement>(null);

// <a> reference type
const linkRef = React.useRef<HTMLLinkElement>(null);

没有错误了,希望这能在某种程度上帮助到其他人,甚至是我自己,P

如果您从外部知道表达式不是空或未定义的,则可以使用非空断言操作符!为了赶走这些类型:

// Error, some.expr may be null or undefined
let x = some.expr.thing;
// OK
let y = some.expr!.thing;