calc-ts
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

calc-ts

CI npm version

Type-level calculator.

Playground

Installation

Using npm:

$ npm install calc-ts

Using yarn:

$ yarn add calc-ts

Example

import type { Calculate } from "calc-ts";

type Result1 = Calculate<"1 + 2">; // 3
type Result2 = Calculate<"1+2+3-4">; // 2
type Result3 = Calculate<"2 * (7 + (8))">; // 30
type Result4 = Calculate<"5 - / 9">; // never

const num1: Calculate<"1 + 4"> = 5; // OK
const num2: Calculate<"1 + 4"> = 6; // Type '6' is not assignable to type '5'.ts(2322)

type ValidExpr<S extends string> = Calculate<S> extends never ? never : S;

function safeEval<S extends string>(expr: ValidExpr<S>): Calculate<S> {
  return eval(expr);
}

const result1 = safeEval("12 + 3"); // 15
const result2 = safeEval("12 = 3"); // Argument of type 'string' is not assignable to parameter of type 'never'. ts(2345)

declare const expr: string;

const result3 = safeEval(expr); // Argument of type 'string' is not assignable to parameter of type 'never'. ts(2345)

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i calc-ts

Weekly Downloads

2

Version

0.1.1

License

MIT

Unpacked Size

13.6 kB

Total Files

9

Last publish

Collaborators

  • dqn