package
TypeScript helpers for nominal typing
npm install nom-tsGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Estimated unpacked size across 1 packages.
14.2 kB
Includes dependencies.
TypeScript helpers for nominal typing
Great! This is easy to fix right? The simple trick below solves the problem.
declare const __brand: unique symbol;
declare const __type: unique symbol;
interface __Brand<T, S extends string> {
[__brand]: S;
[__type]: T;
}
export type Brand<T, S extends string> = T & __Brand<T, S>;But then we encounter some more happy little problems.
type PlayerId = Brand<number, 'PlayerId'>;
type PlayerScores = Record<PlayerId, number>;
const myId = 1337 as PlayerId;
const scores: PlayerScores = { [myId]: 9001 };
// Element implicitly has an 'any' type because expression
// of type 'Brand<number, "PlayerId">' can't be used to
// index type 'Record<Brand<number, "PlayerId">, number>'.
// ts(7053)
const myScore = scores[myId];nom-ts aims to address these problems.
interface __Flavor<T, S extends string> {
[__brand]?: S;
/**
* Intersection is distributive over union, but we don't want to "lose" information about T.
* `__type?: T` will be useful for Unbrand.
*/
[__type]?: T;
}
export type Flavor<T, S extends string> = T & __Flavor<T, S>;
export type Unbrand<T> = T extends Flavor<infer X, any> ?
This project was bootstrapped with TSDX.