typescript - How to suppress error TS2533: Object is possibly null or undefined

typescript – How to suppress error TS2533: Object is possibly null or undefined?

typescript – How to suppress error TS2533: Object is possibly null or undefined?

If you know from external means that an expression is not null or undefined, you can use the non-null assertion operator ! to coerce away those types:

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

This feature is called strict null checks, to turn it off ensure that the --strictNullChecks compiler flag is not set.

However, the existence of null has been described as The Billion Dollar Mistake, so it is exciting to see languages such as TypeScript introducing a fix. Id strongly recommend keeping it turned on.

One way to fix this is to ensure that the values are never null or undefined, for example by initialising them up front:

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

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

See Ryan Cavanaughs answer for an alternative option, though!

typescript – How to suppress error TS2533: Object is possibly null or undefined?

You can suppress if needed, by adding a comment (with CAUTION below)

// @ts-ignore: Object is possibly null.

Not a direct answer to the OPs question, but in my React application with
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 –

const refToElement = useRef(null);

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

CAUTION

Note that since its a compiler error and not the linter error, // tslint:disable-next-line didnt work. Also, as per the documentation, this should be used rarely, only when necessary

UPDATE

With Typescript 3.7 onwards, you can use optional chaining, to solve the above problem as –

refToElement?.current?.focus();

Also, sometimes it just might be a matter of passing in the appropriate type to the generic paramenter, while using useRef.
Eg: In case of an input element –

const refToElement = useRef<HTMLInputElement>(null);

Related posts on typescript  :

Leave a Reply

Your email address will not be published.