Created
November 19, 2022 13:45
-
-
Save IPRIT/0d0c00f82849b2ee47f6773875250a5f to your computer and use it in GitHub Desktop.
Symbol modifiers in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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