Mathjs: Usage with Deno + TypeScript + VS Code

Created on 1 Nov 2020  路  10Comments  路  Source: josdejong/mathjs

What would be steps to have math.js working with TypeScript + Deno and together with intellisense within VS Code??

help wanted question

All 10 comments

That would be interesting to try out!

I haven't tried out Deno myself. As far as I know it should be possible to use JavaScript libraries in Deno. There is also TypeScript definitions for mathjs.

Anyone interested in trying this out?

Hi, I followed the instructions here.

It's a bit messy, but works!

// Needed for VS Code's intellisense
// mathjs.d.ts is local because needs to be edited to properly find Decimal.js
/// <reference path="./mathjs.d.ts" />    

// Load math.js from jspm
import mathjs from "https://dev.jspm.io/mathjs";

// Add types to mathjs. It is necessary to change:
// import { Decimal } from "decimal.js";
// for:
// import { Decimal } from "https://raw.githubusercontent.com/MikeMcl/decimal.js/master/decimal.d.ts";
// in local file mathjs.d.ts
import * as MathJS from "./mathjs.d.ts";  // local file
const math = mathjs as typeof MathJS;

console.log(math.sqrt(-4).toString())
console.log(math.unit(12, 'cm'))

let aunit: math.Unit  // Definition correctly identified by VS Code's intellisense

ow, nice!

Do I understand there is an error in the TypeScript definitions of mathjs mathjs.d.ts?

I don't know if I should call it an _error_. Bear in mind that type-definitions are designed/written to operate in an NPM/Node environment and mathjs.d.ts has no reason to think Decimal.js is not in the local node_modules folder.

Ah, of course, that makes sense. It's a pity that you have to create a manual change in mathjs.d.ts to make it work. Would it be possible to serve the type definition files via jspm too to fix this?

Maybe helpful link: https://github.com/denoland/deno/issues/3196 :)

Well, for now, I've linked it here.

For me esm.sh seems to be working.

import * as mathjs from "https://esm.sh/mathjs";

console.log(mathjs.sqrt(4)) //2
mathjs.foo // Causes typechecking error

Even simpler (thanks to the @deno-types compiler directive). This code assures both intelisense and code compilation. Deno extension has to be installed and loaded (> Deno Init) for the project.

// @deno-types="https://raw.githubusercontent.com/pammacdotnet/FFRepo/master/mathjs.d.ts"
import math from "https://dev.jspm.io/mathjs";
import * as MathJS from "https://raw.githubusercontent.com/pammacdotnet/FFRepo/master/mathjs.d.ts";

const em: math.Unit = math.evaluate("electronMass");
const c = math.evaluate("speedOfLight");
const eenergy: math.Unit = math.multiply(
  em,
  math.pow(c, 2) as math.Unit,
);

console.log(eenergy.toString());

馃憤 thanks for sharing Alberto

Was this page helpful?
0 / 5 - 0 ratings