Skip to content

Instantly share code, notes, and snippets.

@IPRIT
Created November 19, 2022 13:45
Show Gist options
  • Save IPRIT/0d0c00f82849b2ee47f6773875250a5f to your computer and use it in GitHub Desktop.
Save IPRIT/0d0c00f82849b2ee47f6773875250a5f to your computer and use it in GitHub Desktop.
Symbol modifiers in TypeScript
declare const NegativeKey: unique symbol;
declare const PositiveKey: unique symbol;
type Negative<T extends number> = T & { [NegativeKey]?: true };
type Positive<T extends number> = T & { [PositiveKey]?: true };
type IsNegative<T> = keyof NonNullable<T> extends keyof Omit<NonNullable<T>, typeof NegativeKey> ? false : true;
type IsPositive<T> = keyof NonNullable<T> extends keyof Omit<NonNullable<T>, typeof PositiveKey> ? false : true;
type ToNumber<T extends number> = T extends infer N & { [NegativeKey]?: true }
? N
: T extends infer P & { [PositiveKey]?: true }
? P
: T;
type A = Negative<-3>;
type B = Positive<4>;
type C = IsNegative<A>;
type D = IsPositive<A>;
type E = ToNumber<A>;
type F = ToNumber<B>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment