this is my code
export class math {
constructor(number1: number, number2: number):number {
this.num = number1;
this.num2 = number2;
}
add() {
return this.num this.num2
}
}
when i run
console.log(math.add(4, 2)) //or any other number
i get the error..
here is my tsconfig.json
{
"compilerOptions": {
"lib": ["ESNext", "dom", "es6"],
"module": "commonjs",
"moduleResolution": "node",
"target": "ESNext",
"outDir": "dist",
"sourceMap": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true,
"importHelpers": true
},
"exclude": ["./node_modules"]
}
I have tried making it an "any" type it didnt work, i tried alot of other things and it didnt work..
CodePudding user response:
class math {
x: number;
y: number;
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
add() {
console.log(this.x this.y)
}
}
let calculate = new math(1,2)
calculate.add()
CodePudding user response:
You don't need a class to create methods on an object:
const math = {
add (n1: number, n2: number): number {
return n1 n2;
}
};
const sum = math.add(2, 3);
console.log(sum); // 5