#Making conditional types work

3 messages · Page 1 of 1 (latest)

bleak drum
class Test<Bool extends boolean> {
    public msg: Bool extends true ? string : null;

    public constructor() {
        // Type 'null' is not assignable to type 'Bool extends true ? string : null'.ts(2322)
        // What?? null is one of the possible values in the type I defined.
        this.msg = null;
    }

    public boolIsTrue(): this is Test<true> {
        return (typeof this.msg === "string");
    }
}

const inst = new Test();
if (inst.boolIsTrue()) {
    // 'inst.msg' is possibly 'null'.ts(18047)
    // HOW? 'inst' is guaranteed to be of type 'Test<true>' so 'inst.msg' can't be null!
    console.log(inst.msg.at(1))
}

I really, really don't understand what I'm doing wrong. I'd expect the following code to not raise any errors and inst.msg to be correctly inferred as string when inst.boolIsTrue() is true.

NodeJS: 18.17.1
TS: 5.2.2

drowsy brambleBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
plucky oak

[answered in ts server]