diff --git a/src/Type.php b/src/Type.php index f476efd..67fd722 100644 --- a/src/Type.php +++ b/src/Type.php @@ -35,6 +35,18 @@ public function asString(): string return $this->variable; } + /** + * Asserts and narrow down the type to numeric. + */ + public function asNumeric(): int|float|string + { + if (! is_numeric($this->variable)) { + throw new TypeError('Variable is not a numeric.'); + } + + return $this->variable; + } + /** * Asserts and narrow down the type to integer. */ diff --git a/tests/AsNumericTest.php b/tests/AsNumericTest.php new file mode 100644 index 0000000..c242bc8 --- /dev/null +++ b/tests/AsNumericTest.php @@ -0,0 +1,24 @@ +asNumeric(); + + expect($value)->toBeNumeric(); +})->with([ + 7415541, + 7415.541, + "7415541", + 0b01100110, + 0x66, +]); + +test('not numeric type', function () { + $variable = 'string'; + + type($variable)->asNumeric(); +})->with([ + "", + "not numeric", + null, + [] +])->throws(TypeError::class, 'Variable is not a numeric.');