TypeScript: Custom type guards do not work for interfaces

TypeScript Version: 2.2.1 / nightly (2.2.0-dev.201xxxxx)

Code

class mayBeNull {
    importantValue: number | null = null;
    check(): this is checkedCannotBeNull {
        return this !== null;
    }
}

interface checkedCannotBeNull {
    importantValue: number;
}

const obj = new mayBeNull;

obj.importantValue; // "number | null", which is intented

if (obj.check()) {
    obj.importantValue; // Here TypeScript reports "number | (null & number)"
}

Expected behavior: Once a.check() returns true, obj has to be both checkedCannotBeNull and mayBeNull . Hence, obj.number cannot be null because otherwise it will not fulfill interface checkedCannotBeNull.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 16 (11 by maintainers)

Most upvoted comments

I agree, that’s what I said on the second comment 😄