Vidar Vidar - 1 month ago 23
TypeScript Question

Override typing for strict null check

I want to switch to use strict null checks on my typescript 2.0 project, but I'm having some difficulties with the typings of a dependency of one of my dependencies (dependency grandparent if you'd like).

In more detail, I have dependencies

B
and
C
which both depends on
A
. All of these are transpiled TS projects, with code and typings available in a
lib
folder, and they have not yet switched to strict null checks.

The relevant typings in
A
are like follows:

interface IInterface {
[key: string]: string;
}


Which are used in both
B
and
C
as follows:

import { IInterface } from 'A/lib/iinterface';

interface IExtended extends IInterface {
myOptionalProperty?: string
}


With strict null checks, this gives the following compilation error:

node_modules/B/lib/extended.d.ts(4,3): error TS2411: Property 'myOptionalProperty' of type 'string | undefined' is not assignable to string index type 'string'
node_modules/C/lib/extended.d.ts(4,3): error TS2411: Property 'myOptionalProperty' of type 'string | undefined' is not assignable to string index type 'string'


The question is then twofold:


  1. To comply with strict checks, the typing in A needs to be changed to:

    interface IInterface {
    [key: string]: string | undefined;
    }


    I am not sure if it is possible to override such a type, as this is not simply an extension of existing types. If possible, how is it done?

  2. If possible, how should it be included such that the typings in
    B
    and
    C
    are checked against my overridden typing, and not what is in their local
    node_modules
    directory?


Answer

It's possible to just tell the compiler to skip the checks for the libs you are using.
The compiler options now have the skipDefaultLibCheck:

Don’t check a user-defined default library (*.d.ts) file’s validity.

And skipLibCheck:

Don’t check a the default library (lib.d.ts) file’s validity.

So if you compile using that option set to true then you shouldn't get errors for the libs you are using.

There's more about it in the what's new for typescript 2:

TypeScript 2.0 adds a new --skipLibCheck compiler option that causes type checking of declaration files (files with extension .d.ts) to be skipped. When a program includes large declaration files, the compiler spends a lot of time type checking declarations that are already known to not contain errors, and compile times may be significantly shortened by skipping declaration file type checks.

Comments