我有一个类型:

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编译器检查的情况下如何处理这种情况?


当前回答

不是OPs问题,但我通过添加一个空检查来解决这个问题

我改变了:

*ngIf="username.invalid &&  username.errors.required"

To

*ngIf="username.invalid && username.errors != null && username.errors.required"

其他回答

在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
    }

从TypeScript 3.7 (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html)开始,你现在可以使用?。当访问null或未定义对象上的属性(或调用方法)时获得未定义的操作符:

inputEl?.current?.focus(); // skips the call when inputEl or inputEl.current is null or undefined

如果你知道该类型永远不会为null或未定义,你应该声明为foo: Bar,不带?类型声明?条形语法意味着它可能是未定义的,这是您需要检查的。

换句话说,编译器正在做你要求它做的事情。如果您希望它是可选的,您稍后需要检查。

如果需要,您可以通过添加注释来抑制(下面请注意)

// @ts-ignore:对象可能是空的。

不是对OP的问题的直接回答,但在我的React应用程序与 Typescript - v3.6.2 Tslint - v5.20.0

并使用下面的代码

const refToElement = useRef(null);

if (refToElement && refToElement.current) {
     refToElement.current.focus(); // Object is possibly 'null' (for refToElement.current)
}

我通过抑制这一行的编译器继续前进

const refToElement = useRef(null);

if (refToElement && refToElement.current) {
     // @ts-ignore: Object is possibly 'null'.
     refToElement.current.focus(); 
}

谨慎

注意,由于这是一个编译器错误而不是linter错误,// tslint:disable-next-line不起作用。此外,根据文档,这应该很少使用,只在必要时使用

更新

在Typescript 3.7之后,你可以使用可选的链接,来解决上面的问题

refToElement?.current?.focus();

此外,有时可能只是在使用useRef时将适当的类型传递给泛型参数的问题。 在输入元素的情况下-

const refToElement = useRef<HTMLInputElement>(null);

注意:这可能不是一个推荐的操作-也许解决方案是实际解决错误。所有的检查都是有原因的,所以禁用它们并不总是正确的做法,但是……

与上面的一些问题的答案相似,但最后有一点不同。我在多次不同的检查中遇到了问题,帮助我的是在tsconfig.json中设置一个严格的属性为false。似乎是上述特定检查的一种更通用的变体。

  "compilerOptions": {
    "strict": false
  },