i have a function to calculate area of polygon, and here's my function
import {distance} from "mathjs"
function getArea(arrayCord) {
let triangle =[]
let area = 0.0
let a =0.0
let b =0.0
let c =0.0
let s =0.0
for (let i = 0; i < arrayCord.length-2; i ) {
a = distance(arrayCord[i],arrayCord[i 1])// p1-p2
b = distance(arrayCord[i 1],arrayCord[i 2]) //p2 - p3
c = distance(arrayCord[i],arrayCord[i 2]) //p3-p1
s = (a b c)/2;
triangle[i] = Math.sqrt(s*(s-a)*(s-b)*(s-c))
area = triangle[i]
}
return area;
}
when i copy the function into a typescript class and use it, i got this error that said
Operator ' ' cannot be applied to types 'number | math.BigNumber' and 'number | math.BigNumber'
the function in my typescript was
const getArea = (arryy:(number|undefined)[][]) =>{
let triangle =[]
let area = 0.0
let a:(number|BigNumber) =0.0
let b:(number|BigNumber) =0.0
let c:(number|BigNumber) =0.0
let s:(number|BigNumber) =0.0
for (let i = 0; i < arryy.length-2; i ) {
a = distance(arryy[i],arryy[i 1])// p1-p2
b = distance(arryy[i 1],arryy[i 2]) //p2 - p3
c = distance(arryy[i],arryy[i 2]) //p3-p1
s = (a b c)/2;
triangle[i] = Math.sqrt(s*(s-a)*(s-b)*(s-c))
area = triangle[i]
}
return area;
}
how to solve this problem so that i can use my function on my typescript class?
CodePudding user response:
You cannot use regular arithmetic on BigNumber
s.
Replace
s = (a b c)/2
with
s = math.divide(math.add(a, b, c), 2)
But you need to beware that math.divide
returns number | BigNumber | Fraction | Complex | Unit | Array | Matrix
so your s
may need to have its type adjusted.
See:
- https://mathjs.org/docs/reference/functions/divide.html
- https://mathjs.org/docs/reference/functions/add.html
CodePudding user response:
number
and BigNumber
are seen as two data types, and Typescript doesn't know this addition operation is permitted. So in your case, a
could be a number
and b
could be a BigNumber
.
If you know for sure these can be added together, you can use // @ts-ignore I'm sure this adds
on the line above the comment where error is shown.