Is there any way to make two null values distinguishable in TypeScript at type level?

225 Views Asked by At

TypeScript string types can be made unique by adding an extra field with a unique symbol to the type. However, this does not seem to work for null values. See the following example code. Is there any way to make two null values distinguishable at the type level?

// Works with strings

type FooString = string & { readonly _Foo: unique symbol }
type BarString = string & { readonly _Bar: unique symbol }

const fooS: FooString = 'foo' as FooString
// @ts-expect-error FooString is not assignable to BarString
const barS: BarString = fooS


// Does not work with null

type FooNull = null & { readonly _Foo: unique symbol }
type BarNull = null & { readonly _Bar: unique symbol }

const fooN: FooNull = null as FooNull
// @ts-expect-error FooNull is not assignable to BarNull
const barN: BarNull = fooN

export {}

I often work with existing code bases that use null values in various error situations. I am exploring the possibility of adding nominal types to null values as a first step towards more appropriate error handling. The main benefit of using nominally typed null values is that it would let me introduce appropriate type signatures without forcing me to immediately change the runtime implementation.

0

There are 0 best solutions below