If we define a type brand such as:
declare const nominalSymbol: unique symbol;
type Nominal<T extends string, U> = U & { [nominalSymbol]: T };
Is there a way to define a type NotNominal<U>
which resolves to U
if U
is not a branded type.
declare const nominalSymbol: unique symbol;
type Nominal<T extends string, U> = U & { [nominalSymbol]: T };
type BrandedType = Nominal<'Address', string>;
type a = NotNominal<string> // this should be `string`
type b = NotNominal<Address> // this should be `never`
2
Answers
Assert unbranded type
To define a type
NotNominal<U>
that resolvesU
ifU
is not type branded, a conditional type that checks ifU
has the[nominalSymbol]: T
property. If this is the case the type will resolve to never, otherwise it resolves toU
.My example solution of
NotNominal<U>
: