Programing

“오류 TS2533 : 개체가 'null'또는 'undefined'일 수 있습니다.”를 억제하는 방법은 무엇입니까?

lottogame 2020. 6. 15. 08:20
반응형

“오류 TS2533 : 개체가 'null'또는 'undefined'일 수 있습니다.”를 억제하는 방법은 무엇입니까?


나는 type:

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}컴파일러를 진정시키기 위해 명시 적으로 검사를 수행 할 수 있다는 것을 알고 있지만 이것은 사소한 경우에는 매우 적합하지 않은 것 같습니다.

TS 컴파일러 검사를 비활성화하지 않고 어떻게이 상황을 처리 할 수 ​​있습니까?


이 기능은 --strictNullChecks컴파일러 플래그가 설정되어 있지 않은지 확인하기 위해 "엄격한 널 검사"라고 합니다.

그러나 존재 null했다 설명한 바와 같이 억 달러 실수 이므로 같은 타이프가 수정 도입 같은 언어를 표시 흥미 롭다. 전원을 켜두는 것이 좋습니다.

이 문제를 해결하는 한 가지 방법 은 예를 들어 을 미리 초기화 하여 값이 절대 null또는 아닌지 확인하는 undefined것입니다.

interface SelectProtected {
    readonly wrapperElement: HTMLDivElement;
    readonly inputElement: HTMLInputElement;
}

const selectProtected: SelectProtected = {
    wrapperElement: document.createElement("div"),
    inputElement: document.createElement("input")
};

당신이 표현이 아니라고 외부 수단에서 알고있는 경우 null또는 undefined, 당신은 null이 아닌 주장 연산자를 사용하여 !그 유형을 멀리 강요 :

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

나는 사용했다 :

if (object !== undefined) {
    // continue - error suppressed when used in this way.
}

또는 유형 강제를 사용할 수 있습니다.

const objectX = object as string

위의 해결 방법 중 하나를 선택하기 전에 원하는 아키텍처를 고려하고 더 큰 그림에 영향을 미칩니다.


유형이 절대로 null또는 이 아님을 알고 undefined있으면를 foo: Bar없이 선언해야 합니다 ?. ? Bar구문을 사용 하여 형식을 선언하면 형식 이 정의되지 않았을 수 있습니다. 이는 확인할 사항입니다.

다시 말해, 컴파일러는 요청한 내용을 정확하게 수행합니다. 선택 사항으로하려면 나중에 확인해야합니다.


이 솔루션은 저에게 효과적이었습니다.

  • tsconfig.json으로 이동하여 "strictNullChecks"를 추가하십시오 .

enter image description here


이것은 OP의 문제는 아니지만 Object is possibly 'null'우연히 null 유형으로 매개 변수를 선언했을 때 동일한 메시지가 나타납니다.

something: null;

null 값을 할당하는 대신 :

something: string = null;

As an option, you can use a type casting. If you have this error from typescript that means that some variable has type or is undefined:

let a: string[] | undefined;

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

Be sure that a really exist in your code.


Tip for RxJS

I'll often have member variables of type Observable<string>, and I won't be initializing it until ngOnInit (using Angular). The compiler then assumes it to be uninitialized becasue it isn't 'definitely assigned in the constructor' - and the compiler is never going to understand ngOnInit.

You can use the ! assertion operator on the definition to avoid the error:

favoriteColor!: Observable<string>;

An uninitialized observable can cause all kinds of runtime pain with errors like 'you must provide a stream but you provided null'. The ! is fine if you definitely know it's going to be set in something like ngOnInit, but there may be cases where the value is set in some other less deterministic way.

So an alternative I'll sometimes use is :

public loaded$: Observable<boolean> = uninitialized('loaded');

Where uninitialized is defined globally somewhere as:

export const uninitialized = (name: string) => throwError(name + ' not initialized');

Then if you ever use this stream without it being defined it will immediately throw a runtime error.


In ReactJS, I check in the constructor if the variables are null, if they are I treat it like an exception and manage the exception appropriately. If the variables are not null, code carries on and compiler does not complain anymore after that point:

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
    }

I ran in to this with React when setting state and using map.

In this case I was making an API fetch call and the value of the response wasn't known, but should have a value "Answer". I used a custom type for this, but because the value could be null, I got a TS error anyway. Allowing the type to be null doesn't fix it; alternatively you could use a default parameter value, but this was messy for my case.

I overcame it by providing a default value in the event the response was empty by just using a ternary operator:

this.setState({ record: (response.Answer) ? response.Answer : [{ default: 'default' }] });

In typescript you can do the following to suppress the error:

let subString?: string;

subString > !null; - Note the added exclamation mark before null.


If you're having this problem with refs in React, strict null checks should be enough:

if (inputEl && inputEl.current) {
     inputEl.current.focus();
}

More here


Not a direct answer to the OP's question, but in my case, I had the following setup -

Typescript - v3.6.2
tslint - v5.20.0

And using the following code

const refToElement = useRef(null);

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

I moved on by suppressing the compiler for that line. Note that since it's a compiler error and not the linter error, // tslint:disable-next-line didn't work. Also, as per the documentation, this should be used rarely, only when necessary -

const refToElement = useRef(null);

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

참고URL : https://stackoverflow.com/questions/40349987/how-to-suppress-error-ts2533-object-is-possibly-null-or-undefined

반응형