Comment

Comment by eyelidlessness

I’ve spent way too much time trying to perfect this technique and the best solution (until TS has nominal types, which I think they’re looking at for 4.5) is branding, with a private declared class field that’s optional and always never. Eg

    declare class _MySpecialPrimitive {
      private mySpecialPrimitive?: never;
    }

    type MySpecialPrimitive = number & _ MySpecialPrimitive;
Combined with type guards (which you can conditionally execute at runtime), you can narrow overly broad structural types safely, eg:

    const isMySpecialPrimitive(val: unknown): val is MySpecialPrimitive => /* anything that produces a boolean */
(And you can use assert guards in a similar way, but I find they make it easier to treat them as a noop)

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton