type-fest
Version:
A collection of essential TypeScript types
58 lines (44 loc) • 1.86 kB
TypeScript
import type {IsAny} from './is-any.d.ts';
import type {IsNever} from './is-never.d.ts';
import type {UnwrapBrandedPrimitive} from './unwrap-branded-primitive.d.ts';
/**
Returns a boolean for whether the given number is a float, like `1.5` or `-1.5`.
Checks union members separately, so mixed results return `boolean`. Returns `boolean` for `any`, and `false` for `never`, `unknown`, and the widened `number` type.
Use-case:
- If you want to make a conditional branch based on the result of whether a number is a float or not.
@example
```
import type {IsFloat, PositiveInfinity} from 'type-fest';
type A = IsFloat<1.5>;
//=> true
type B = IsFloat<-1.5>;
//=> true
type C = IsFloat<1e-7>;
//=> true
type D = IsFloat<1.0>;
//=> false
type E = IsFloat<PositiveInfinity>;
//=> false
type F = IsFloat<1.23e+21>;
//=> false
```
@category Type Guard
@category Numeric
*/
// Plain primitives need no unwrapping; branded or tagged intersections are normalized because `${T}` does not reduce for a literal intersected with an object type.
export type IsFloat<T> =
// `any` is not a float and is not the absence of one either, so it answers `boolean`, the same as `IsInteger` does for it. `IsNumericLiteral`, `IsBooleanLiteral`, `IsStringLiteral` and `IsSymbolLiteral` answer `false` for `any` instead, because each of them narrows to one kind of literal, while a number may be either a float or an integer.
// `any` is checked before `never`, so generic code that wraps the result and infers from it still sees both outcomes.
IsAny<T> extends true
? boolean
: IsNever<T> extends true
? false
: _IsFloat<T extends object ? UnwrapBrandedPrimitive<T> : T>;
type _IsFloat<T> = T extends number
? `${T}` extends `${number}e+${number}`
? false
: `${T}` extends `${number}.${number}` | `${number}e-${number}`
? true
: false
: false;
export {};