uhyo / better-typescript-lib

Better TypeScript standard library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Make `Boolean()` a type guard

somebody1234 opened this issue · comments

Open in playground

interface BooleanConstructor {
  <T>(value?: T): value is Exclude<T & {}, null | undefined | 0 | 0n | false | "">;
}

const what = Math.random() > 0.5 ? 1 : Math.random() > 2 ? false : null;
what;
// ^? - const what: false | 1 | null
if (Boolean(what)) {
  what;
  // ^? const what: 1
}

(The & {} is necessary in case T is unknown, for example)

not 100% sure whether there are any issues with this, of course. the else case might be wrong, i guess? specifically the else case might be missing 0 | 0n | ""

commented

I looked into this. Unfortunately this cannot be done in a type safe way without negated types. 😢

Playground Link

declare const myBoolean: {
  <T>(value?: T): value is Exclude<T & {}, null | undefined | 0 | 0n | false | "">;
};

const what = Math.random() > 0.5 ? 1 : Math.random() > 2 ? 0 : null;
what;
// ^?
if (myBoolean<number | null>(what)) {
  what;
  // ^?
} else {
  what;
  // ^?
  if (what !== null) {
    what;
    // ^?
    // Oops, what is never here
    const a: { boom(): void } = what;
    a.boom();
  }
}