1

TypeScript の文字列型は、一意の記号を持つフィールドを型に追加することで一意にすることができます。ただし、これは null 値に対しては機能しないようです。次のコード例を参照してください。型レベルで 2 つの null 値を区別できるようにする方法はありますか?

// 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 値に公称型を追加する可能性を探っています。名目上型指定された null 値を使用する主な利点は、ランタイムの実装をすぐに変更しなくても、適切な型シグネチャを導入できることです。

4

0 に答える 0