Ts-morph: Possible bug with Type.isNullable()?

Created on 25 Jun 2019  路  3Comments  路  Source: dsherret/ts-morph

I am experiencing unexpected behavior regarding detection of a nullable type within an interface property using Type.isNullable(). (As a novice user I might be doing something silly, but I have been struggling with this for quite a while and cannot find a way out.)

Here is a simple source file interfaces.ts defining an interface

export interface Sandwich {
    extraSauce: null | string;
}

and a main index.ts

import { Project, ts, TypeGuards } from "ts-morph";

const project = new Project({});

project.addExistingSourceFiles("interfaces.ts");

console.log("TS version: " + ts.version);

const sourceFile = project.getSourceFileOrThrow("interfaces.ts");
const interfaces = sourceFile.getInterfaces();

interfaces.forEach(itf => {
    console.log(itf.getName());

 itf.getProperties().forEach(prop => {
        const typeNode = prop.getTypeNode()!;
        const type = typeNode.getType();
        console.log(
            "Name: " + prop.getName() + "\n" +
            "Text: " + type.getText() + "\n" +
            "Is nullable: " + type.isNullable() + "\n" +
            "Union types: " + (TypeGuards.isUnionTypeNode(typeNode) ? typeNode.getTypeNodes().map(t => t.getText()).join(" ") : "") +
            "\n"
        );
    });
});


I obtain the following output:

TS version: 3.5.2
Sandwich
Name: extraSauce
Text: extraSauce: string   <--- expected null | string;
Is nullable: false         <--- expected true
Union types: null string

Note how checking for union type through typeNode works as expected.

question

Most helpful comment

Hey @claudv, you'll need to enable the strict null checks compiler option. Otherwise the type checker ignores undefined/null in union types and thinks all types are not nullable.

const project = new Project({
    compilerOptions: {
        strictNullChecks: true
    }
});

I was confused by that too when I first started... it's disabled by default in the compiler api (this project uses the same defaults as the compiler api).

All 3 comments

Hey @claudv, you'll need to enable the strict null checks compiler option. Otherwise the type checker ignores undefined/null in union types and thinks all types are not nullable.

const project = new Project({
    compilerOptions: {
        strictNullChecks: true
    }
});

I was confused by that too when I first started... it's disabled by default in the compiler api (this project uses the same defaults as the compiler api).

Many thanks, again. Sorry for spamming you bug reports.

@claudv it's really no problem! No need to apologize. Keep filing issues!

I'm sure other people will run into this issue so it's good to have it in the issue tracker.

Was this page helpful?
0 / 5 - 0 ratings