我有一个类型:

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


当前回答

从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

其他回答

从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

作为一个选项,您可以使用类型强制转换。如果你从typescript中得到这个错误,这意味着某些变量有类型或未定义:

let a: string[] | undefined;

let b: number = a.length; // [ts] Object is possibly 'undefined'
let c: number = (a as string[]).length; // ok

确保代码中确实存在a。

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

list!.values

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

list?.values

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

useRef

像这样使用useRef钩子

const value = inputRef?.current?.value

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

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

尝试像这样调用object:

(<any>Object).dosomething

出现此错误是因为您使用?将它们声明为可选。Typescript会做严格的检查,它不允许做任何未定义的事情。因此,您可以在这里使用(<any> youobject)。