Borek Borek - 1 month ago 21
TypeScript Question

TypeScript strict null checks: how to override library constraint?

My code is using the

async
library, specifically this callback type (source):

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


In my TypeScript code with
strictNullChecks
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
err
optional, like this:

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


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

Answer

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;
    }
}
Comments