TypeScript 字符串类型可以通过向类型添加一个带有唯一符号的额外字段来使其唯一。但是,这似乎不适用于空值。请参阅以下示例代码。有什么方法可以在类型级别区分两个空值?
// 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 {}
我经常使用在各种错误情况下使用空值的现有代码库。我正在探索将名义类型添加到 null 值的可能性,作为更适当的错误处理的第一步。使用名义上类型化的 null 值的主要好处是它可以让我引入适当的类型签名,而不会强迫我立即更改运行时实现。