UNPKG

type-fest

Version:

A collection of essential TypeScript types

61 lines (45 loc) • 1.49 kB
import type {UnwrapBrandedPrimitive} from './unwrap-branded-primitive.d.ts'; import type {PositiveInfinity} from './numeric.d.ts'; /** Returns the absolute value of the specified number or bigint. @example ``` import type {Absolute} from 'type-fest'; type A = Absolute<-1>; //=> 1 type B = Absolute<1>; //=> 1 type C = Absolute<0>; //=> 0 type D = Absolute<-1.025>; //=> 1.025 type E = Absolute<-9999n>; //=> 9999n ``` Returns back the same type if the input is not a literal type. @example ``` import type {Absolute} from 'type-fest'; type A = Absolute<number>; //=> number type B = Absolute<bigint>; //=> bigint type C = Absolute<number | bigint>; //=> number | bigint ``` @category Numeric */ // The brand is removed first, because `${N}` does not reduce for a literal intersected with an object type, so a branded literal would be returned unchanged. export type Absolute<N extends number | bigint> = _Absolute<N extends object ? UnwrapBrandedPrimitive<N> : N>; type _Absolute<N extends number | bigint> = N extends bigint // Also, distributes `N` ? `${N}` extends `-${infer Magnitude extends bigint}` ? Magnitude : N : `${N}` extends `-${infer Magnitude extends number}` ? Magnitude // `-Infinity` does not infer a numeric magnitude, so handle it separately. : `${N}` extends '-Infinity' ? PositiveInfinity // A computed numeric enum member prints like `number`, so its magnitude is unknown too. : `${number}` extends `${N}` ? number : N; export {};