by koblas · 8y ago · 0 comments
The best tagging mechanism these days is `Nominal<T>` (which has no emit) or `As<T>` (which has a minimal amount of emit):
interface Nominal<T> {
'nominal type tag': T
}
class As<T> {
private tag: T
}
Both are used in the same manner: const enum SomeTag { }
type Something = number & As<SomeTag>
// or
type Something = number & Nominal<SomeTag>
You can even avoid the boilerplate of `const enum` if you make the `T` of `As` or `Nominal` `T extends string`: type Something = number & As<'some:unique:string:tag'>
In both cases, the values are not unified, so: type Something = number & As<'kind1'>
type SomethingElse = number & As<'kind2'>
var x: Something = 123 as Something;
var y: SomethingElse = 456 as SomethingElse;
x = y; // Type 'SomethingElse' is not assignable to type 'Something'.https://basarat.gitbooks.io/typescript/docs/tips/nominalTypi...
(edit:) Ah ha! "Because numbers are type compatible with enums the previous technique cannot be used for them."