Borek Borek - 1 year ago 216
TypeScript Question

TypeScript strict null checks: how to override library constraint?

My code is using the

library, specifically this callback type (source):

interface AsyncResultCallback<T> { (err: Error, result: T): void; }

In my TypeScript code with
enabled, calling it like this fails:

cb(null, someObject);

Error:(239, 16) TS2345: Argument of type 'null' is not assignable to parameter of type 'Error'.

Now I'm not sure whether the library type definition is wrong or not but let's say it is and the interface should be defined with
optional, like this:

interface AsyncResultCallback<T> { (err?: Error, result: T): void; }

What can I do to persuade TypeScript to allow passing
as the first parameter of the callback? I've already tried
"skipLibCheck": true
"skipDefaultLibCheck": true
but no joy.

Answer Source

The skipLibCheck and skipDefaultLibCheck flags won't help in this case because the error is from your code and not from the library you are using.

You have two options (that I can think of):

(1) Pass a non-null value:

cb(new Error(), someObject);

(2) Try to augment the library:

import * as Async from "async";

declare global {
    interface AsyncResultCallback<T> {
        (err: Error | null, result: T): void;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download